Reputation: 223
I need some help with regular expressions in JavaScript.
I have the following string.
var str = "SOme TEXT #extract1$ Some more text #extract2$ much more text #extract3$ some junk";
I want to extract all the text between #
and $
into an array or object.
Final output would be:
var result = [extract1,extract2,extract3]
extract1, extract2,extract3 can contain any characters like _,@,&,*
Upvotes: 1
Views: 795
Reputation: 15172
You can use JavaScript Regular expressions' exec method.
var regex = /\#([^\$]+)\$/g,
match_arr,
result = [],
str = "some #extract1$ more #extract2$ text #extract3$ some junk";
while ((match_arr = regex.exec(str)) != null)
{
result.push(match_arr[1]);
}
console.log(result);
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec
Upvotes: 2
Reputation: 11788
Regex for you will be like #(?<extract>[\s\S]*?)\$
Named group 'extract'will contain the values you want.
As Alex mentioned, if javascript doesnt support named group, we can use numbered group. So modified regex will be #([\s\S]*?)\$
and desired values will be in group number 1.
Upvotes: 2