Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html tag attribute values using JavaScript Regular Expressions?

Suppose I have this HTML in a string:

<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE">
<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">
<meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">

And I have this regular expression, to get the values inside the content attributes:

/<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig

How do I, in JavaScript, get all three content values?

I've tried:

var setCookieMetaRegExp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;
var match = setCookieMetaRegExp.exec(htmlstring);

but match doesn't contain the values I need. Help?

Note: the regular expression is already correct (see here). I just need to match it to the string. Note: I'm using NodeJS

like image 949
Obay Avatar asked Jan 24 '14 03:01

Obay


2 Answers

You were so close! All that needs to be done now is a simple loop:

var htmlString = '<meta http-equiv="Set-Cookie" content="COOKIE1_VALUE_HERE">\n'+
'<meta http-equiv="Set-Cookie" content="COOKIE2_VALUE_HERE">\n'+
'<meta http-equiv="Set-Cookie" content="COOKIE3_VALUE_HERE">\n';

var setCookieMetaRegExp = /<meta http-equiv=[\"']?set-cookie[\"']? content=[\"'](.*)[\"'].*>/ig;

var matches = [];
while (setCookieMetaRegExp.exec(htmlString)) {
  matches.push(RegExp.$1);
}

//contains all cookie values
console.log(matches);

JSBIN: http://jsbin.com/OpepUjeW/1/edit?js,console

like image 70
Sean Johnson Avatar answered Oct 03 '22 01:10

Sean Johnson


Keep it simple:

/content=\"(.*?)\">/gi

demo: http://regex101.com/r/dF9cD8

Update (based on your comment):

/<meta http-equiv=\"Set-Cookie\" content=\"(.*?)\">/gi

runs only on this exact string. Demo: http://regex101.com/r/pT0fC2

You really need the (.*?) with the question mark, or the regex will keep going until the last > it finds (or newline). The ? makes the search stop at the first " (you can change this to [\"'] if you want to match either single or double quote).

like image 43
Floris Avatar answered Oct 03 '22 00:10

Floris