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?
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With