0

I want replace M in the following text with April

Sample Text:

dddd yy aM5 May May SUM MMMM 56 MM M

Expected result:

dddd yy aApril5 May Mars SUM MMMM 56 MM April


Really i want ignore replacment when:

  • M is start of May and Mars
  • M is between some M Like: MMMM or MM or MMM
  • M is end of SUM

I tried the following code but it dose not exclude special words from replacement:

text.replace(/[^May|Mars|MMMM|MM|MMM|SUM]M/g,"April")

// Incorrect result>>   dddd yy aM5AprilayAprilay SUMAprilMMM 56AprilMApril
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
  • You need to read a tutorial that eplains what `[]` means in regexp. It has nothing to do with excluding words like that. – Barmar May 31 '17 at 18:55
  • 2
    What you want to do requires a negative lookbehind, but Javascript doesn't have this. Read https://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent for workarounds. – Barmar May 31 '17 at 18:56

1 Answers1

4

A simple way would be matching all those unwanted parts first:

var text = 'dddd yy aM5 May May SUM MMMM 56 MM M';
console.log(text.replace(/\bM(?:a(?:y|rs)|M+)|SUM|(M)/g, function(match, p1) {
    return p1 ? 'April' : match;
}));
revo
  • 47,783
  • 14
  • 74
  • 117