【发布时间】:2013-11-01 22:23:00
【问题描述】:
我知道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 的解决方案以在第 nth 个正则表达式出现时拆分字符串的任何想法?
【问题讨论】:
标签: javascript regex arrays string split