Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string in between two strings [duplicate]

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?

like image 608
MarksCode Avatar asked Dec 06 '25 08:12

MarksCode


1 Answers

You can use the regex

play\s*(.*?)\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 = /play\s*(.*?)\s*in/g;

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

document.body.innerHTML = '<pre>' + JSON.stringify(matches, 0, 4) + '</pre>';
like image 121
Tushar Avatar answered Dec 08 '25 20:12

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!