简体   繁体   中英

string.replace does not work with regex

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:

  1. It's better to escape all curly brackets. Your pattern will work well without escaping them, but it's a good idea to indicate that it's just a regular text.
  2. Parentheses are redundant in your case, because you don't do anything with the catched string between curly braces.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM