我需要按字符串 !
(前后空格)和一个字符 |
拆分字符串。
function split (str) {
return str.split (/\s!\s/)
}
result = split ("hello world ! hello | world! hi ");
console.log (result); // result must be: ["hello world", "hello", "world! hi "]
我不知道该怎么做。现在我所做的只是通过 !
进行拆分。加上char |
需要筛选,因为在正则表达式中是OR
的意思。
最佳答案
听起来你想要这样的东西:
function split (str) {
return str.split (/\s[!|]\s/)
}
这将通过 !
或 |
分隔字符串,后者被空白字符包围。
您可以看到它正在运行 here .
但一般来说,如果您想使用 |
(或任何特殊字符)作为文字,您可以使用反斜杠 (\
) 将其转义,如下所示:
/\s!\s|\s\|\s/
关于javascript - 如何用两个正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952002/