1
正則表達式的第n次出現的字符串,我知道split
可以得到第二個參數的限制,但它不是我要找的。我知道這可以通過分割並再次連接一個固定的字符串分隔符來完成。拆分在JavaScript的
的問題是分隔符是一個正則表達式,我不知道,匹配模式的精確長度。
考慮這個字符串:
this is title
--------------------------
rest is body! even if there is some dashes.!
--------
---------------------
it should not counted as a separated part!
通過使用這樣的:
str.split(/---*\n/);
我會得到:
[
'this is title',
'rest is body! even if there is some dashes.!',
'',
'it should not counted as a separated part!'
]
而這正是我想要的:(如果我想通過第一次出現)
分裂[
'this is title',
'rest is body! even if there is some dashes.!\n--------\n---------------------\nit should not 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次出現分裂的字符串。您的解決方案僅在第一次出現時拆分字符串。 –
埃米爾,舉例說明源文本和第N次出現(N = 2或更多)情況下的結果。 – ReinRaus
想象一下這個字符串:'this ----- that --- these ------ those'。如果N = 2(1型)時,結果應該是:[「這個-----即」,「這些------那些」] –