Why does my regex not work inside string.match()?

177 Views Asked by At

I think that this regex should work:

/(?s)\<strong\>.+\<\/strong\>/

It validates and matches everything between <strong> tags at regex101.com.

However, it doesn't match anything when I use it in the regex match() method.

var string = "text text <strong>some text</strong> text text";

var re = /(?s)\<strong\>.+\<\/strong\>/;

alert(string.match(re));

This should alert the <strong> tags and everything in between. However, it doesn't work at all.

Why is this, and how can I fix it?

3

There are 3 best solutions below

5
On BEST ANSWER

The leading (?s) is an invalid group in a JavaScript regex. The browser console surely produced an error when you tried that.

You don't need to escape < or >, so this works:

var re = /<strong>.+<\/strong>/;

Note that if you have several <strong> elements in a run of text, your regular expression will match everything from the first <strong> to the last </strong>, because the + quantifier is greedy. You can change that:

var re = /<strong>.+?<\/strong>/;
0
On

If you try it in browser js console(Ctrl + Shift +K in firefox) you will get error SyntaxError: invalid regexp group

It works without (?s) part, you don't need it

var string = "text text <strong>some text</strong> text text";

var re = /\<strong\>.+\<\/strong\>/;

alert(string.match(re));
0
On

Javascript won't support (?s) DOTALL modifier. So use [\S\s] instead of . in your regex.

<strong>[\s\S]+<\/strong>  // greedy match

For non-greedy match, you need to add the quantifier ? next to the + symbol.

<strong>[\s\S]+?<\/strong>

[\s\S]+ matches also the newline characters but .+ won't match line breaks.

> var string = "text text <strong>some text</strong> text text";
undefined
> var re = /<strong>[\s\S]+?<\/strong>/;
undefined
> console.log()

undefined
> console.log(string.match(re));
[ '<strong>some text</strong>',
  index: 10,
  input: 'text text <strong>some text</strong> text text' ]