Reputation: 81
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';
Upvotes: 0
Views: 564
Reputation: 370619
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:
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.
Upvotes: 2
Reputation: 15489
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
Upvotes: 1