Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript match: return only subpattern matched contents

Tags:

javascript

"unescape('awefawef')unescape('efawefwf')unescape('awefawef')"
.match(/unescape\(\'([^\)]+)\'\)/gi)

If there multiple unescape(...) matches it returns matches with unescape, but i need only what is inside () brackets.

Thanks ;)

Desired output:

['awefawef','efawefwf','awefawef']
like image 407
Somebody Avatar asked Feb 24 '23 09:02

Somebody


2 Answers

You will need to use the ungreedy operator to match only the contents of the parenthesis, and to get all results, you will need to call RegExp.exec multiple times on the same string.

var regex = /unescape\('(.+?)'\)/ig;
var string = "this unescape('foo') is a unescape('bar') test";
var result;
while(result = regex.exec(string))
    console.log(result[1]);
like image 165
Alex Turpin Avatar answered Mar 02 '23 18:03

Alex Turpin


You can get it from RegExp.$1.

"unescape('awefawef')unescape('efawefwf')unescape('awefawef')".match(/unescape\(\'([^\)]+)\'\)/gi);
console.log(RegExp.$1); //awefawef
like image 32
bjornd Avatar answered Mar 02 '23 19:03

bjornd