javascript - 根据多个分隔符拆分字符串 [/, #, @, '' ]

标签 javascript regex string split

我想根据多个分隔符拆分一个字符串。

如何用多个字符串作为分隔符拆分一个字符串?

例如:

我有一个字符串:"/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

如何解决?有什么帮助吗? :-(

最佳答案

这里是没有Regx的解决方案

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",['/','#','@',"'"])

输出

Array [ "", "create ", "channel ", "name", " ", "description of the channel", " ", "field1 ", "field2" ]

关于javascript - 根据多个分隔符拆分字符串 [/, #, @, '' ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32754177/

相关文章:

javascript - .onclick 按钮不执行功能

php - 删除依赖于 RegEx 类的 CSS 规则

javascript - 用于避免仅输入数字的正则表达式(不输入任何其他字符)

c# - for 循环中的子字符串提取的字符多于应有的字符

javascript - 带有正则表达式的文本字段的电话掩码

javascript : How to filter text without spell checking?

python - 格式化日期、时间和文件名字符串

c - 用户输入字符串(使用 fgets)中最后一个字符的 ASCII 值输出为 10,而预期值为 0

javascript - 将对象数组传递给 react 组件

Javascript:在文档中查找 URL