skip to Main Content

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


  1. You can iterate over the usernames and replace them if they exist with the desired format:

    let str = 'Hi @john.doe, i see @john has tagged you, reply back to @john!';
    const usernames = new Map([['john.doe', 1], ['john', 2]]);
    
    [...usernames.entries()].forEach(([u, i]) => {
      const reg = new RegExp(`@${u}(?![a-z0-9_.-])`, 'g');
      if (str.match(reg)) {
        str = str.replace(reg, `${u}(${i})`);
      }
    });
    
    console.log(str);
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search