4

I have a regex pattern that matches leading characters before (a, b, c or i) in only the first word of a string: /^\s*[^abci]+(?=\w)/i such that:

"sanity".replace(/^\s*[^abi]+(?=\w)/i, (pattern) => 'v');
  // "vanity"

How do i define the regex newRegex such that it matches leading characters in every word of a string so that:

 "sanity is a rice".replace(newRegex, (pattern) => 'v');

outputs:    vanity is a vice

3
  • 1
    Try .replace(/\b[^\Wabi]/gi, 'v') Commented Jul 21, 2018 at 8:36
  • /.../g = global flag to ensure all possible matches, not just the first one Commented Jul 21, 2018 at 8:42
  • Another similar: /\b[^abi]\B/gi Commented Jul 21, 2018 at 9:38

2 Answers 2

2

It seems to me you want to replace any word char other than a, b, i at the beginning of a word.

You may use

.replace(/\b[^\Wabi]/gi, 'v')

See the regex demo.

  • \b - a word boundary
  • [^\Wabi] - a negated character class that matches any char other than a non-word char (so, all word chars are matched except the chars that are also present in this class), a, b and i.

The global modifier g is added so as to match all occurrences.

JS demo:

console.log(
     "sanity is a rice".replace(/\b[^\Wabi]/gi, 'v')
);

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

Comments

2

You can also try using split() and map() to remove the first char and get the desired output:

function replaceChar(str){
  var matchChar = ['a', 'b', 'c', 'i'];
  var changedArr = str.split(/\s+/).map((item) => {
    if(matchChar.includes(item.charAt(1))){
      return 'v' + item.substr(1, item.length);
    }
    return item;
  });
  return changedArr.join(' ');
}
var str = 'sanity is a rice';
console.log(replaceChar(str));
str = 'This is a mice';
console.log(replaceChar(str));

2 Comments

Question is "replace with regEx", why are you not making use of that ?.
@AkhilAravind you should read what i said You can also try ? Notice that also there? This is a suggested answer.

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.