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
>Solution :
You can split on capturing word characters with a capture group
var str = "(someword,bbb)";
console.log(str.split(/(\w+)/));
You could also specify the characters to split on using a character class [(),] and remove empty entries if neccesary:
var str = "(someword,bbb)";
console.log(str.split(/([(),])/).filter(Boolean));