0

I want to convert "me" to "you", without touching words that have "me" in them, i.e.
"awesome melon me" -> "awesome melon you"

So far I got the negative look ahead pattern:

str.replace(/me(?![a-zA-Z])/g, 'you')

so I get

"awesome melon me" -> "awesoyou melon you"

Tried some answers already, couldn't find someone that matches this request, thanks in advance for the help

goldylucks
  • 4,697
  • 3
  • 35
  • 40

3 Answers3

4

You could use the zero-width \b special symbol to ensure to match "me" when it's a complete word:

"awesome melon me".replace(/\bme\b/g, "you")
// returns "awesome melon you"
janos
  • 115,756
  • 24
  • 210
  • 226
0

You can use word boundary as suggested in other answers, which keeps me345 or hello_me as well. If you need a more strict matching pattern, you can capture the matched letter before the pattern, and put it in the replacement pattern.

var s = "me awesome melon me"
console.log(s.replace(/(^|[^a-zA-Z])(me)(?![a-zA-Z])/g, '$1you'));
Psidom
  • 195,464
  • 25
  • 298
  • 322
0

This should do it: str.replace(\bme\b/g, 'you') - \b looks for a word boundary.