Reputation: 3543
I faced a simple but wired issue when I tried to replace a simple string:
const reference = 'then Max have gone with Sara.';
const selector = 'sara';
const phrase = 'Joe';
const result = reference.toLowerCase().replace(selector, phrase);
console.log(result);
I have a reference
string and I want to replace a selector
with a phrase
.
The issue is the selector may be all lowercase so I need to conver reference to all lowercase words to be able to implement the replace method on two all lowercase strings right?
Now the issue shows up... when I convert the reference to lowercase words then all capital words (like Max as a name!) turn to lower case unexpectedly...
How can I do the replace method and still get this result:
then Max have gone with Joe.
Upvotes: 0
Views: 29
Reputation: 386654
You could build a regular expression (RegExp
) with some flags, like g
for global (replace all ocurrences) and i
for case insensitive search.
This approach does not cover special characters, but all letters and digits.
const
reference = 'then Max have gone with Sara.',
selector = 'sara',
phrase = 'Joe',
result = reference.replace(new RegExp(selector, 'gi'), phrase);
console.log(result);
console.log('foo.'.replace(new RegExp('.', 'gi'), '!')); // all chars are replaced
Upvotes: 2