javascript - get substring until nth match regex - Stack Overflow

Let's say I have the string:"Hello world; some random text; foo; bla bla; "what regular

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
Add a ment  | 

4 Answers 4

Reset to default 4

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;

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

相关推荐

  • javascript - get substring until nth match regex - Stack Overflow

    Let's say I have the string:"Hello world; some random text; foo; bla bla; "what regular

    7小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信