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)
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)
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
Edit 1: handle either order of attributes
Edit 2: handle single or double quotes, case insensitivity, and spacing