拆分一个字符串,但保留逗号

时间:2022-05-04 00:25:03

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

1 个解决方案

#1


2  

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);

#1


2  

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);