我需要拆分一个保留非空格的句子字符串,例如.
或,
。我需要将它们包含在要拆分的数组字符串中。不在它们自己单独的数组索引中。
const regex = /\W(?:\s)/g
function splitString (string) {
return string.split(regex)
}
console.log(splitString("string one, string two, thing three, string four."))
// Output ["string one", "string two", "thing three", "string four."]
// Desired ["string one,", "string two,", "string three,", "string four."]
最佳答案
也许使用匹配方法而不是拆分方法:
"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g);
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ]
或更具体的(这样您可以轻松选择一个或多个分隔符):
"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g);
关于javascript - 拆分字符串但保留逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44969074/