简体   繁体   English

分割字符串但保留逗号

[英]Split a string but keep the Comma

I need to split a sentence string that keeps the non-whitespace such as . 我需要拆分一个保留非空格的句子字符串,例如. or , . 或者, I need them to be included within the array string being split. 我需要将它们包含在要拆分的数组字符串中。 Not in their own seperate array index. 不在自己的单独数组索引中。

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."]

Perhaps using a match approach instead of a split approach: 也许使用匹配方法而不是拆分方法:

"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g);
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ]

or something more specific (this way you can easily choose one or several delimiter characters) : 或更具体的内容(通过这种方式,您可以轻松选择一个或几个定界符)

"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM