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 regex split string into array pattern

Should be trivial but I’ve struggled over this simple issue:

Example string:
#anchor1: text including special chars like % #anchor2:text has # char

should get splitted in:

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

[#anchor1: text including special chars like %]
[#anchor2:text has # char]

anchors have always a hash followed by any character followed by a colon.

I’ve tried #\S+:[^#+] but this stops at the # inside anchor2

>Solution :

ChatGPT says:

Hey! To split the string into an array using the given pattern, you can use JavaScript’s str.match method with the appropriate regex pattern. The regex pattern should look for a sequence that starts with #, followed by any characters, and ending with a :. Then it should capture everything until the next sequence that matches the pattern.

Here’s a quick code snippet to do that:

const str = "#anchor1: text including special chars like % #anchor2:text has # char";
const regex = /(#\w+:.*?)(?=#\w+:|$)/g;
const result = str.match(regex);
console.log(result);

This will output:

[ '#anchor1: text including special chars like % ', '#anchor2:text has # char' ]

Hope this helps! Let me know if you have more questions.

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