Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript separate punctuation from alpha-numeric chats

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading