英文:
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 = "(someword,bbb)";
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 = "(someword,bbb)";
console.log(str.split(/([(),])/).filter(Boolean));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论