我想根据多个分隔符拆分字符串。
如何将一个字符串拆分为多个字符串作为分隔符?
例如:
我有一个字符串:"/create #channel 'name' 'description of the channel' #field1 #field2"
我想要一个数组:
/create
#channel
name
description of the channel
#field1
#field2
另一个例子,我有:"/send @user 'A messsage'"
而且我要:
/send
@user
A message
怎么解决呢?有什么帮助吗? :-(
这是没有正则表达式的解决方案
var multiSplit = function (str, delimeters) {
var result = [str];
if (typeof (delimeters) == 'string')
delimeters = [delimeters];
while (delimeters.length > 0) {
for (var i = 0; i < result.length; i++) {
var tempSplit = result[i].split(delimeters[0]);
result = result.slice(0, i).concat(tempSplit).concat(result.slice(i + 1));
}
delimeters.shift();
}
return result;
}
只需使用
multiSplit("/create #channel 'name' 'description of the channel' #field1 #field2",['/','#','@',"'"])
output
Array [ "", "create ", "channel ", "name", " ", "description of the channel", " ", "field1 ", "field2" ]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)