hia*_*iok 4 javascript string split
正常拆分的工作方式如下:
var a = " a @b c "
console.log(a.split(" "))
["", "a", "b", "c", ""]
Run Code Online (Sandbox Code Playgroud)
但我的预期输出是:[" a", "@b", "c "]有可能吗?如何?
一种选择是使用正则表达式并在空格之前和之后需要字边界:
var a = " a b c "
console.log(a.split(/\b \b/));Run Code Online (Sandbox Code Playgroud)
如果允许使用非单词字符,则可以使用match- 在字符串开头匹配空格,后跟非空格,或匹配非空格,后跟空格和字符串结尾,或匹配非没有限制的空间:
const a = " foo @bar c "
console.log(
a.match(/^ *\S+|\S+ *$|\S+/g)
);Run Code Online (Sandbox Code Playgroud)
Lookbehind是另一种选择,但它还不足以支持生产代码中的可靠性.
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |