Search code examples
javascriptnode.jsregexstring

How to replace all occurrences of a string except the first one in JavaScript?


I have this string:

hello world hello world hello world hello

and I need to get the following:

hello world hello hello hello

If I use:

str = str.replace('world', '');

it only removes the first occurrence of world in the above string.

How can I replace all the occurrences of it except the first one?


Solution

  • You can pass a function to String#replace, where you can specify to omit replacing the first occurrence. Also make your first parameter of replace a regex to match all occurrences.

    Demo

    let str = 'hello world hello world hello world hello',
        i = 0;
        
    str = str.replace(/world/g, m  => !i++ ? m : '');
    console.log(str);

    Note

    You could avoid using the global counter variable i by using a IIFE:

    let str = 'hello world hello world hello world hello';
    
    str = str.replace(/world/g, (i => m => !i++ ? m : '')(0));
    console.log(str);