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

RegEx Split String and Leave Delimiter

I am trying to split a string and leave the delimiter intact. I am getting pretty close but I can’t figure it out fully. I have found a lot of examples on Stack Overflow but I am still running in to an issue that I can’t figure out. Here is the code:

"This is a string with ${G:VarSome:G} text".split(/\$\{(.+?(}\(.+?\)|}))/g)

The above code yields:

['This is a string with ', 'G:VarSome:G}', '}', ' text']

The result I am looking for is:

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

['This is a string with ', '${G:VarSome:G}', ' text']

The ${G:SomeVar:G} pattern is a templating system where variables will be injected. There are other formats of variables too for example ${G:AnotherVar:1}, ${G:DifferentVar:5} etc. After I get the split string, I will do a variable lookup in the system to inject the corresponding variable.

>Solution :

You are having an extra capture group inside the regex, this will give you a single group.

/(\$\{.+?})/g

This should capture the examples provided. regex101

const result = "This is a string with ${G:VarSome:G} text".split(/(\$\{.+?})/g);

console.log(result);
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