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;"
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;"
Share
Improve this question
edited Jan 11, 2012 at 5:17
xkeshav
54.1k47 gold badges181 silver badges251 bronze badges
asked Jan 11, 2012 at 5:15
Tono NamTono Nam
36.2k84 gold badges326 silver badges492 bronze badges
4 Answers
Reset to default 4Try 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;
If you don't have to use Regex, you could use the Split() method with a semicolon separator:
http://www.w3schools./jsref/jsref_split.asp
I don't think this is a problem that is best solved with RegExps. Very easy to do it with straight JS. http://jsfiddle/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.
why regex??
do it in simple way
var str = "Hello world; some random text; foo; bla bla; "
alert(str.split(";",2).join(";"));
reference
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745247318a4618468.html
评论列表(0条)