JQuery get text from inside string

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



JQuery get text from inside string



I have a string of text and I want to get the text from inside the 'this-name' attribute. I searched but have only found examples of getting text from div attributes.


var text = 'blah blah this-name="GET THIS TEXT" blah blah';




2 Answers
2



Use a regular expression to match what comes after the this-name, enclosing the text between the quotes in a group. Then, just extract the first group from the match:


match


this-name




var text = 'blah blah this-name="GET THIS TEXT" blah blah';
const extractedText = text.match(/this-name="([^"]+)"/)[1];
console.log(extractedText);



If the string is an HTML string, you should probably use something like DOMParser instead.



For multiple matches, use a loop and iterate through each match:




const text = 'blah blah this-name="GET THIS TEXT" blah blah this-name="GET THIS TEXT 2" etc';
const output = ;
const re = /this-name="([^"]+)"/g;
let match;
while ((match = re.exec(text)) !== null)
output.push(match[1]);

console.log(output);



You could also use lookbehind to get all matches instead of the while loop, but lookbehind is only supported in the newest of browsers, so it shouldn't be relied on.


while





How would this work with multiple 'this-name', if i wanted to get all the 'this-name' results? var text = 'blah blah this-name="GET THIS TEXT 1" blah blah, 'blah blah this-name="GET THIS TEXT 2" blah blah';
– lanjes
Aug 12 at 10:23






Make the regular expression global, and then iterate through the matches in a while loop, like here stackoverflow.com/questions/31776624/…
– CertainPerformance
Aug 12 at 10:31





would you be able to edit your answer to show this?
– lanjes
Aug 12 at 10:33





Ok, see edit...
– CertainPerformance
Aug 12 at 10:36



You can split the original string at 'this-name="' and get the last portion (which will give you the name text, trailing quote and remainder of the text) and then split the resultant string at '"' and take the first portion (which will give you simply the text of the name attribgute that you are after.




var text = 'blah blah this-name="GET THIS TEXT" blah blah';

var nameText = text.split('this-name="')[1].split('"')[0]

console.log(nameText); // gives GET THIS TEXT






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS