将JavaScript中的标点符号与字母数字字符分开。

huangapple go评论94阅读模式
英文:

Javascript separate punctuation from alpha-numeric chats

问题

我正在尝试拆分以下字符串,以便得到一个包含n个元素的数组,例如:
var str = "(someword,bbb)"
所以数组将是
var arr = ["(", "someword", ",", "bbb", ")"]

我尝试使用split和正则表达式,但实际上它会删除那些标点符号,而我需要它们仍然可用。这个可能吗?

非常感谢提前帮助!

使用带标点符号的正则表达式进行拆分,但标点符号没有被保留。

英文:

I'm trying to split a string like the following in order to have a array of the n elements, for example:
var str = "(someword,bbb)"
So the array would be
var arr = ["(", "someword", ",", "bbb", ")"]

I tried with split and regex but it actually removes those punctuation marks while I need them to be still available. Is this even possible?

Many thanks in advance

Split with punctuation regex but punctuation marks are not kept

答案1

得分: 2

你可以使用捕获组来分割捕获的单词字符。

var str = "(someword,bbb)";
console.log(str.split(/(\w+)/));

你也可以使用字符类 [(),] 来指定分割的字符,并且如果需要的话,可以删除空条目:

var str = "(someword,bbb)";
console.log(str.split(/([(),])/).filter(Boolean));
英文:

You can split on capturing word characters with a capture group

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var str = &quot;(someword,bbb)&quot;;
console.log(str.split(/(\w+)/));

<!-- end snippet -->

You could also specify the characters to split on using a character class [(),] and remove empty entries if neccesary:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var str = &quot;(someword,bbb)&quot;;
console.log(str.split(/([(),])/).filter(Boolean));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年8月9日 05:16:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定