[英]Split string to only return the substring prior to the nth occurrence of a delimiter in JavaScript
[英]Split a string at nth occurrence of a regex in javascript
我知道split
可以獲得第二個參數作為限制,但這不是我想要的。 而且我知道它可以通過使用實心字符串分隔符拆分和再次連接來完成。
問題是分隔符是一個正則表達式,我不知道匹配模式的確切長度。
考慮這個字符串:
this is a title
--------------------------
rest is body! even if there are some dashes!
--------
---------------------
it should not be counted as a separated part!
通過使用這個:
str.split(/---*\n/);
我會得到:
[
'this is a title',
'rest is body! even if there are some dashes.!',
'',
'it should not be counted as a separated part!'
]
這就是我想要的:(如果我想在第一次出現時拆分)
[
'this is a title',
'rest is body! even if there are some dashes.!\n--------\n---------------------\nit should not be counted as a separated part!'
]
這個解決方案是我目前所擁有的,但這只是第一次出現。
function split(str, regex) {
var match = str.match(regex);
return [str.substr(0, match.index), str.substr(match.index+match[0].length)];
}
關於如何推廣任何數字n的解決方案以在第 n次出現正則表達式時拆分字符串的任何想法?
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);
輸出:
["this-----that", "these------those"]
js小提琴
功能選項:
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);
具有功能 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.