Ole
Ole

Reputation: 46890

Conditional replacement of a string using regex?

I need to replace all occurrences of @example/ in a file, unless the complete match is @example/is.

Currently I have this code:

 let updated = s.replace(/@example\//g, replacement);

However this will update all occurrences, including the ones with @example/is. How do we exclude the @example/is occurrences in the file?

Addendum

I'm just pasting in the script I used (which incorporates the great answer) to perform the updates, in case anyone else needs to do something like this:

const fs = require("fs");
const globby = require("globby");
globby("./test/**/*.ts")
  .then(paths => {
    paths.forEach(update);
  })
  .catch(e => console.log(e));

function update(path) {
  let replacement = "@ex/";
  let js = fs.readFileSync(path, "utf8");
  js = js.replace(/@example\/(?!is)/g, replacement)
  fs.writeFileSync(path, js);
}

Upvotes: 3

Views: 528

Answers (1)

anubhava
anubhava

Reputation: 784898

You can use a negative lookahead assertion:

let updated = s.replace(/@example\/(?!is)/g, replacement)

(?!is) is a negative lookahead assertion that will fail the match when is comes after @example/

Upvotes: 7

Related Questions