Reputation: 2165
I'm trying to find complete words in a string, but I'm having trouble where the word occurs after hyphen. How do I create the regex to ignore the words that occur after hyphen?
var text = "google e-google alphagooglebeta google google";
var word = "google";
var regex = new RegExp("\\b" + word + "\\b", "g");
var result = text.replace(regex, "SUCCESS");
output: "SUCCESS e-SUCCESS alphagooglebeta SUCCESS SUCCESS"
expected output: "SUCCESS e-google alphagooglebeta SUCCESS SUCCESS"
Upvotes: 1
Views: 50
Reputation: 785256
You can use:
var text = "google e-google alphagooglebeta google google";
var word = "google";
var regex = new RegExp("(^|\\s)" + word + "(?=\\s|$)", "g");
var result = text.replace(regex, "$1SUCCESS");
console.log(result);
//=> SUCCESS e-google alphagooglebeta SUCCESS SUCCESS
Regex /(^|\s)google(?=\s|$)/
matches google
if it is preceded by start or whitespace. We capture this part in a capturing group.
(?=\s|$)
is zero-width lookahead assertion that asserts that we have a whitespace or line end ahead.
Upvotes: 2