James G.
James G.

Reputation: 2904

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?

Upvotes: 1

Views: 639

Answers (1)

SLaks
SLaks

Reputation: 887453

You have two options:

  1. Use lookahead:

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

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

Upvotes: 4

Related Questions