javascript - 拆分字符串但保留逗号

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

最佳答案

也许使用匹配方法而不是拆分方法:

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

关于javascript - 拆分字符串但保留逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44969074/

相关文章:

python - 从python中的多值元素数组打印特定值

javascript - 使用正则表达式,如何检查倒数第二个字符是否为奇数

javascript - 确保以 JSON 格式接收 HTTP POST 请求并使用 REST API 将其保存到 MySQL

javascript - 使用 .filter 从数组中删除项目并返回新数组

javascript - 如何在1秒内只更换一次背景图片

javascript - 使用 Javascript 服务器端编码从经典 ASP 返回 JSONP

javascript - 简单的 JavaScript 游戏 [Mastermind] 问题

arrays - 将字符分配给每列中的唯一字符串并将值重置为该字符

java - 如何用正则表达式去除字符串

javascript - 检查一个单词是否以元音开头?