Regular expression in javascript

here is the code

var str = 'a girl is reading a book!';
var reg =  /\w*(?=ing\b)/g;
var res = str.match(reg);
console.log(res);

      

result: ["read", ""] in chrome.

I want to ask why the result is "".

+3


source to share


2 answers


Expected behavior

The first read

is fixed as it follows ing

. Here ing

only matches. It is never included in the result.



Now we are in position after read

, i.e. are in i

.. here again ing

matches (because of \w*

) and gives an empty result because there is no between reading and ing.

You can use \w+(?=ing\b)

to avoid empty result

+7


source


/\w*(?=ing\b)/g


Here you are using *

which means "no" or "more". Therefore, it captures both "read"ing

, and ""ing

after reading the part read

. Use + for one or more.



+2


source