Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 is ["read",""] in chrome.

I wanna ask why there is "" in the result.

like image 352
user1990553 Avatar asked Jan 14 '23 08:01

user1990553


2 Answers

This is expected behaviour

First read is captured since it is followed by ing.Here ing is only matched..It is never included in the result.

Now we are at the position after read i.e we would be at i..here again ing matches(due to \w*) and it gives an empty result because there is nothing between read and ing.

You can use \w+(?=ing\b) to avoid the empty result

like image 146
Anirudha Avatar answered Jan 16 '23 21:01

Anirudha


/\w*(?=ing\b)/g
Here you are using * which means none or more, Hence it captures both "read"ing and ""ing after it reads the read part. Use + for one or more.

like image 34
ppsreejith Avatar answered Jan 16 '23 22:01

ppsreejith