简体   繁体   中英

Split a string at nth occurrence of a regex in javascript

I know split can get a second parameter as a limit, but it is not what I'm looking for. And I know it can be done by splitting and joining again with a solid string delimiter.

The problem is the delimiter is a regular expression and I don't know the exact length of the pattern that matches.

Consider this string:

this is a title
--------------------------
rest is body! even if there are some dashes!
--------
---------------------
it should not be counted as a separated part!

By using this:

str.split(/---*\n/);

I will get:

[
  'this is a title',
  'rest is body! even if there are some dashes.!',
  '',
  'it should not be counted as a separated part!'
]

And this is what I wanted to be: (if I want to split by the first occurrence )

[
  'this is a title',
  'rest is body! even if there are some dashes.!\n--------\n---------------------\nit should not be counted as a separated part!'
]

This solution is what I currently have, but it's just for the first occurrence.

function split(str, regex) {
    var match = str.match(regex);
    return [str.substr(0, match.index), str.substr(match.index+match[0].length)];
}

Any ideas on how to generalize the solution for any number n to split the string on the n th occurrence of regex?

var str= "this-----that---these------those";
var N= 2;
var regex= new RegExp( "^((?:[\\s\\S]*?---*){"+(N-1)+"}[\\s\\S]*?)---*([\\s\\S]*)$" );
var result= regex.exec(str).slice(1,3);
console.log(result);

Output:

["this-----that", "these------those"]

jsFiddle
Option with the function:

var generateRegExp= function (N) {
    return new RegExp( "^((?:[\\s\\S]*?---*){"+(N-1)+"}[\\s\\S]*?)---*([\\s\\S]*)$" );
};

var getSlice= function(str, regexGenerator, N) {
    return regexGenerator(N).exec(str).slice(1,3);
};

var str= "this-----that---these------those";
var N= 2;
var result= getSlice(str, generateRegExp, N);
console.log(result);

jsFiddle

Option with the function 2:

var getSlice= function(str, regex, N) {
    var re= new RegExp( "^((?:[\\s\\S]*?"+regex+"){"+(N-1)+"}[\\s\\S]*?)"+regex+"([\\s\\S]*)$" );
    return re.exec(str).slice(1,3);
};

var str= "this-----that---these------those";
var N= 3;
var result= getSlice(str, "---*", N);
console.log(result);

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM