0

I have the following regex that returns keyword values:

 var keywords = result.match(/<meta name="keywords" content="(.*?)".*/i)[1];

I also need to be able to support situations where the "keywords" and the "content" properties are in the reverse order e.g:

<meta content="...." name="keywords"

Can anyone advise how I can support both orders?

Ben
  • 6,026
  • 11
  • 51
  • 72
  • If that regex works, I wouldn't try to over-complicate things, just use another one with name and content reversed and then check which one returned values. – aurbano Mar 31 '14 at 09:37
  • Can't you just target the given `meta[name=keyword]` element? – eithed Mar 31 '14 at 09:38

2 Answers2

1

THE PONY HE COMES

With access to the DOM at your fingertips, you have no excuse not to dump your HTML into a temporary document (or, if it's the current document, work on it from there). Then, depending on browser version, you can just querySelector("meta[name=keywords]") or iterate through getElementsByTagName('meta') until you find the right one, before using getAttribute("content") to get the result.

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Use positive lookahead to check first that the name="keywords" exists, then parse content.

var keywords = result.match(/<meta(?=[^>]*\bname="keywords")[^>]*\bcontent="(.*?)".*/i)[1];
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85