Javascript 拆分字符串,但保留逗号
我需要拆分一个保留非空白的句子字符串,如Javascript 拆分字符串,但保留逗号,javascript,arrays,regex,split,Javascript,Arrays,Regex,Split,我需要拆分一个保留非空白的句子字符串,如或,。我需要将它们包含在被拆分的数组字符串中。不在自己单独的数组索引中 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",
或,
。我需要将它们包含在被拆分的数组字符串中。不在自己单独的数组索引中
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);