kent ilyuk
kent ilyuk

Reputation: 129

Javascript replace exact match w/o specialchars

bar foo: baz qux bar foo baz foo; bar

In this string I want to replace only the foo

I tried \bfoo\b but it replaces all occurrences. How can I replace the exact word with regex?

Upvotes: 0

Views: 697

Answers (2)

melpomene
melpomene

Reputation: 85837

"bar foo: baz qux bar foo baz foo; bar".replace(/(^|\s)foo(?!\S)/g, "$1hello")

The cleanest solution would be to use look-behind; unfortunately JavaScript doesn't support that. As a workaround, we capture the preceding whitespace character (or beginning of string) and re-insert it with the replacement (that's the $1 part).

Upvotes: 1

Scimonster
Scimonster

Reputation: 33409

It sounds like you just want to replace the one with spaces around it. For that, just do / foo /, with spaces.

\b matches words, and punctuation is considered word delimiters.

To match it if it's at the beginning or end too, i would use a lookahead: /(?=^|\s)foo(?=\s|$)/

Upvotes: 2

Related Questions