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

时间:2017-07-07 10:56:28

标签: 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", "string two", "thing three", "string four."]
// Desired ["string one,", "string two,", "string three,", "string four."]

1 个答案:

答案 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);
相关问题