admin管理员组文章数量:1416050
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
本文标签: javascriptget substring until nth match regexStack Overflow
版权声明:本文标题:javascript - get substring until nth match regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745247317a2649613.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论