Tono Nam
Tono Nam

Reputation: 36070

get substring until nth match regex

Let's say I have the string:

"Hello world; some random text; foo; bla bla; "

what regular expresion could I use in order to get a substring until the second ; .

In other words I will like to end up with the substring "Hello world; some random text;"

or maybe I want to get the substring until the 3th ; thus ending up with:

"Hello world; some random text; foo;"

Upvotes: 1

Views: 2650

Answers (4)

yumitsu
yumitsu

Reputation: 599

Try this one. Should work just fine.

/([\w\s]+?\;){2}/

Used as follows:

var str = "Hello world; some random text; foo; bla bla; ";
var match = str.match(/([^;]*;){2}/)[0];
alert(match); // Hello world; some random text;

Upvotes: 4

xkeshav
xkeshav

Reputation: 54084

why regex??

do it in simple way

var str = "Hello world; some random text; foo; bla bla; "
alert(str.split(";",2).join(";"));

reference

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92334

I don't think this is a problem that is best solved with RegExps. Very easy to do it with straight JS. http://jsfiddle.net/mendesjuan/xvM53/1/

var str = "Hello world; some random text; foo; bla bla; ";
function getParts(str, delimiter, partCount) {
  return str.split(delimiter,partCount).join(";");
}

Credit where it's due: I shamelessly used diEcho's idea, I didn't remember you could pass a second parameter to split.

Upvotes: 1

Brian Snow
Brian Snow

Reputation: 1143

If you don't have to use Regex, you could use the Split() method with a semicolon separator:

http://www.w3schools.com/jsref/jsref_split.asp

Upvotes: 2

Related Questions