Thursday, 21 July 2016

Javascript - Regex access multiple occurrences




I have this text




txt = "Local residents o1__have called g__in o22__with reports...";


in which I need to get the list of numbers between each o and __



If I do



txt.match(/o([0-9]+)__/g);



I will get



["o1__", "o22__"]


But I'd like to have



["1", "22"]



How can I do that ?


Answer



See this question:



txt = "Local residents o1__have called g__in o22__with reports...";
var regex = /o([0-9]+)__/g
var matches = [];
var match = regex.exec(txt);
while (match != null) {

matches.push(match[1]);
match = regex.exec(txt);
}
alert(matches);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...