Reputation: 159
I'm trying to replace some words in a string with .replace(desiredWord,"")
, to remove those words from that string.
I have a string which is like this "xsmall small medium"
and I'm trying to remove "small"
from that string in some events, but it sometimes removes small of xsmall
also, which is not my intention..
Is there any way to restrict replace method or I should use another method?
I want to replace or remove specific word, not letters.
Upvotes: 2
Views: 1478
Reputation: 13304
The following should work:
If you pad your desiredWord
with the word boundary \b
operator it will work without false positives.
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/\bsmall\b/g, "test"));
With variable
document.querySelector("#replace").addEventListener("click", (e) => {
debugger
const value = document.querySelector("#change").value;
//escape the operators in the regexp!
const regex = new RegExp("\\b"+value+"\\b", "g");
document.querySelector("#text").value = document.querySelector("#text").value.replace(regex, "test");
}, true);
<input readonly id="text" value="xsmall small medium" /><br />
<input id="change"><button id="replace">Replace</button>
Upvotes: 2
Reputation: 765
You can use a RegEx
expression for this.
You can use these in the replace method directly.
A way to check this is using the next expression: \bsmall
The result of this is as follow :
string.replace(\bsmall, "")
\b
will check if the characters are from 1 and only 1 word
Upvotes: 2
Reputation: 5631
You could exclude letters before explicitly:
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/([^a-z])(?=small)/ig, "$1x");
This regular expression reads, "Not a letter, followed by (but not captured) 'small', replaced with whatever the non-letter was, followed by an x."
or the same thing using the word boundary feature, just be sure not to delete it too:
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/(\b)(?=small)/ig, "$1x");
This one reads, "Any word boundary, followed by 'small' (but without 'small' forming part of the replacement), replaced by the word boundary and then an 'x'.
Upvotes: 1