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

TypeScript Replace function does not work if there are multiple cases

For creating some shortcodes, in TypeScript I replace a string with another string.

This looks like this:

output = output.replace(/\[+([^\][]+)]+/g,"<?php echo $settings['$1'] ?>");
output = output.replace(/\{+([^\][]+)}+/g,"<?php echo $settings['$1']['url'] ?>");

So this code:

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

<a href="[link]" class="test">
    <img src="{hoverimage}">
    <img src="{image}">
</a>

should be translated into this:

<a href="<?php echo $settings['link'] ?>" class="test">
    <img src="<?php echo $settings['hoverimage']['url'] ?>">
    <img src="<?php echo $settings['image']['url'] ?>">
</a>

What does not work

For some reason I get this:

<a href="<?php echo $settings['link'] ?>" class="test">
    <img src="<?php echo $settings['hoverimage}">
    <img src="{image']['url'] ?>">
</a>

So the problem are the parts with the brackets {}. Interesting: When I only have one line with brackets it works well. For example if I remove the second img, the replacing function works well.

Why this happens? Do you have an idea?

>Solution :

your current logic catches start of first match, and end of second match. to get rid of it use nongreedy search, by adding ? to + so it would become +?

output = output.replace(/\{+([^\][]+?)}+/g,"<?php echo $settings['$1']['url'] ?>");
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