简体   繁体   中英

Javascript RegExp replace. How to carry unknown characters into replacement?

I'm trying to get a much deeper understanding of JS RegExp for a project I'm working on.

So if I were checking for all strings containing foo and then a character that is not a number, I would use /foo[^0-9]/ . However, let's say I want to change all strings matching that pattern to foobar and then the original characters, how would I go about that?

str = foozip;
newStr = str.replace(/foo[^0-9]/, "foobar");
console.log(newStr);
//returns foobarip Note the lack of a z.

str = foozip;
newStr = str.replace(/foo/, "foobar");
console.log(newStr);
//this matches foo6zip, which is no good

Do I have to run a separate check to do this? Is there a way to carry unknown characters from one side of a replace to the other?

You have two options:

  1. Use lookahead:

     str.replace(/foo(?=[^0-9])/, "foobar") 
  2. Use capture groups:

     str.replace(/foo([^0-9])/, "foobar$1") 

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