I have this string dfdfd dsfsdfsdfsdf {{random.number}} dsfdsfsdfsdf {{bla}}
and simple code that shold replace any {{...}}
in a given string:
const b = template.replace(/\{{(.*)\}}/g, 'aaaa');
but nothing happened template.replace
just does not work however the regex seems to be matching all {{}}
Any thougts?
UPDATE:
Just realized that my input string was wrong. Now I have all working with my original regex. However thanks to @Robo-Robok now I learned about greedy
regexes and will be using his regex intstead.
Regular expressions are greedy by default. Your .*
eats as much as it can, which includes the first }}
pair.
Try this instead:
const b = template.replace(/\{\{.*?\}\}/g, 'aaaa');
Question mark after *
, ?
makes the match non-greedy.
Also two things:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.