3

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);
}

1 Answer 1

7

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.