I’m trying to replace occurences in a string into something else. Lets say I have the following sentence:
Hi @john.doe, i see @john has tagged you
I have 2 usernames in this sentence: @john
and @john.doe
. I want this to become this sentence:
Hi @john.doe(1), i see @john(2) has tagged you
I’m doing it like this:
Text = text.replace(username, ‘${username}(${userId})’);
The problem is, when I loop over all usernames in the string and do a replace for each username, because @john
is a username but also a part of another username, it doesn’t work.
How can I replace exact words in a string in js?
2
Answers
You can iterate over the usernames and replace them if they exist with the desired format:
Can you try to sort your usernames in descending order by their lengths, then try to replace/apply those in the given string? That’ll resolve your issue. Just make sure that while replacing values, if an id is already appended to a username, then skip those. Try this and let me know if this works for you.