-1

I need to select local stylesheets from an HTML string in JavaScript. How can I turn the following into a regex?

(file.indexOf('<link rel="stylesheet"') === 0) && (file.indexOf('href="http') === -1)
elixenide
  • 44,308
  • 16
  • 74
  • 100
alpar
  • 1,577
  • 1
  • 10
  • 7

1 Answers1

1

Don't parse HTML with regex! HTML is not a regular language, and you will get much better results with a parser. For example, what if the rel attribute comes after the href attribute? That's valid HTML syntax, but not a scenario you are currently trying to handle. This could cause problems.

But if you insist, you could do this:

/<link (?=[^>]*rel=\s*['"]stylesheet['"])(?![^>]*href=\s*['"]http)[^>]*>/i

Demo

Edit 1: handle either order of attributes

Edit 2: handle single or double quotes, case insensitivity, and spacing

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • Should use case insensitivity too, though this can fail because of single (or no) quotes. – Lye Fish Apr 18 '15 at 14:48
  • var my_string = (document.head || document.getElementsByTagName('head')[0]).innerHTML; (my_string.match(/]*rel="stylesheet")(?![^>]*href="http)[^>]*>/i) == (my_string.indexOf(' – GramThanos Apr 18 '15 at 14:48
  • @ThanasisGrammatopoulos I'm not really sure what you're saying. Are you saying the regex doesn't produce the same results as the original logic? If so, the test case (the HTML for the `` in question) would be more useful than the JS code you posted. – elixenide Apr 18 '15 at 14:54
  • I agree, i think the question is wrong... The first .indexOf shoulden't be >=0 ? – GramThanos Apr 18 '15 at 14:58