我需要拆分保留非空格的句子字符串,例如.
或,
。我需要将它们包含在被拆分的数组字符串中。不在他们自己的单独数组索引中。
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."]
答案 0 :(得分:2)
也许使用匹配方法而不是拆分方法:
"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);