Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  147] [ 6]  / answers: 1 / hits: 16450  / 8 Years ago, fri, february 26, 2016, 12:00:00

If I have a string like this:



var str = play the Ukulele in Lebanon. play the Guitar in Lebanon.;


I want to get the strings between each of the substrings play and in, so basically an array with the Ukelele and the Guitar.



Right now I'm doing:



var test = str.match(play(.*)in);


But that's returning the string between the first play and last in, so I get the Ukulele in Lebanon. Play the Guitar instead of 2 separate strings. Does anyone know how to globally search a string for all occurrences of a substring between a starting and ending string?


More From » regex

 Answers
96

You can use the regex



plays*(.*?)s*in




  1. Use the / as delimiters for regex literal syntax

  2. Use the lazy group to match minimal possible



Demo:



var str = play the Ukulele in Lebanon. play the Guitar in Lebanon.;
var regex = /plays*(.*?)s*in/g;

var matches = [];
while (m = regex.exec(str)) {
matches.push(m[1]);
}

document.body.innerHTML = '<pre>' + JSON.stringify(matches, 0, 4) + '</pre>';




[#63150] Wednesday, February 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adam

Total Points: 363
Total Questions: 102
Total Answers: 104

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;