Reputation: 285
I have the following regex:
<div\s*class="selectionDescription">(.*?)<\/div>
Which works with PHP perfectly. I am aware that javascript does not support the \s flag.
I have tried using the \g flag, however my pattern is not matched.
I am looking to match everything inside the div in the following string:
<div class="selectionDescription">Text to match</div>
I receive the following error in javascript:
Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 's'(…)
Upvotes: 0
Views: 83
Reputation: 4069
If you are spanning multiple lines, and you mean the single line
mode that s
provides, you can emulate that with [\S\s]
or some other similar "all inclusive, all exclusive" style: [\d\D]
, [\W\w]
, etc.
That will allow it to span multiple lines and still match:
<div\s*class="selectionDescription">([\S\s]*?)<\/div>
You need to be wary of using lazy *?
quantifiers, however. Take a look at https://regex101.com/r/xD2jV8/1 where the number of steps is 220.
If the content between <div>
and </div>
tags is very large, this becomes very computationally expensive, very fast.
While slightly less readable,
<div\s*class="selectionDescription">((?:[^<]+|<(?!\/div>))*)<\/div>
would do the same but within only 69 steps.
And at that point, https://regex101.com/r/xD2jV8/3 slightly optimizes it further, but HTML really isn't the best way to handle things with HTML. jQuery could perform this quickly and much "safer": $('div.selectionDescription').html()
Of course, you may not have access to this at this point, but HTML is usually not the best thing to use for parsing HTML.
Upvotes: 2
Reputation: 6664
s
is not a flag, so if you are trying something like new RegExp('<div\s*class="selectionDescription">(.*?)<\/div>', 's')
then yes, you would find an error.
You do not need to add any flags, except perhaps the g
flag to capture this div many times. (Check it out)
Maybe check out a quick primer on Javascript's regular expressions?
Upvotes: 2