Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
karlosuccess Avatar asked Apr 24 '18 23:04

karlosuccess


People also ask

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do you remove all occurrences of a character from a string in JavaScript?

Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.

How do you replace a character in a string in JavaScript without using replace () method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.


1 Answers

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);
like image 63
Kristianmitk Avatar answered Sep 18 '22 06:09

Kristianmitk