javascript – Regex to match all the words between curly brackets, squared brackets and signs
Inside my string there are different tags that I have to match with a regex and then wrap with some extra tags I have to use.
Let’s say I have this string:
Lorem ipsum <key="right_outline"> sed [heal] dolor {sit} amet, {0:%s} consectetur {BBBw}
{/BBBw} adipiscing <color=#CC294B></color> elit. Sed [copd][cc] lobortis mauris.
So I need a regex to match everything that is between these tags as <…> and {…} and <…>.
Also I have to wrap every single combination with <my-tag></my-tag>
as in the example here:
Lorem ipsum <my-tag><key="right_outline"></my-tag> sed <my-tag>[heal]</my-tag>
dolor <my-tag>{sit}</my-tag> amet, <my-tag>{0:%s}</my-tag> consectetur
<my-tag>{BBBw}{/BBBw}</my-tag> adipiscing <my-tag><color=#CC294B></color></my-tag> elit.
Sed <my-tag>[copd][cc]</my-tag> lobortis mauris.
I am new to the regex so having some test with this:
let regex_tags = new RegExp("\[.*?\]|{.*?}|<.*?>");
And for the Javascript part about putting the wrapping tags:
a="my string with all the weird tags on it";
r = new RegExp("\[.*?\]|{.*?}|<.*?>");
b = a.replace(r, `<my-tag>$&</my-tag>`);
I use the $& into the .replace() method to let the matches be preserved and not modified, just wrapped.
Questions:
- Do any of you know a regex to achieve this?
- Is the .replace() method the best solutions?
Thanks a lot for the help
Read more here: Source link
