Reputation: 466
I need to replace all matching words or special characters in a string, but cant figure out a way to do so.
For example i have a string: "This - is a great victory"
I need to replace all -
with +
signs. Or great
with unpleasant
- user selects a word to be replaced and gives replacement for it.
"\\b"+originalTex+"\\b"
was working fie until i realised that \b does work only with word characters.
So the question is: what is replacement for \b would let me replace any matching word that is enclosed by whitespaces?
EDIT: I can not remove word boundaries as it would result inexact match. For example: you are creator of your world, while change you, your also would be changed. as it contains "you"
Upvotes: 2
Views: 2332
Reputation: 627101
You need to use the following code:
var s = "you are creator of your world";
var search = "you";
var torepl = "we";
var rx = new RegExp("(^|\\s)" + search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "(?!\\S)", "gi");
var res = s.replace(rx, "$1" + torepl);
console.log(res);
The (^|\\s)
will match and capture into Group 1 start of string or a whitespace. The search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
will escape special chars (if any) inside the search word. The (?!\\S)
lookahead will require a whitespace or end of string right after the search word.
The $1
backreference inserts the contents of Group 1 back into the string during replacement (no need to use any lookbehinds here).
Upvotes: 2
Reputation: 178328
How about two replaces
var txt = "This - is a great, great - and great victory"
var originalTex1 = "great",originalTex2 = "-",
re1 = new RegExp("\\b"+originalTex1+"\\b","g"),
re2 = new RegExp("\\s"+originalTex2+"\\s","g")
console.log(txt.replace(re1,"super").replace(re2," + "))
Upvotes: 1