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

Shining Love Star
  • 5,734
  • 5
  • 39
  • 49

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
  • 120,954
  • 29
  • 226
  • 236
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
  • 209,562
  • 33
  • 339
  • 356
0

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