How to replace all occurrences of a string except the first one in JavaScript?
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);
var str = 'hello world hello world hello world hello';
var count = 0;
var result = str.replace(/world/gi, function (x) {
if(count == 0) {
count++;
return x;
} else {
return '';
}
});
console.log(result);
In my solution, I am replacing first occurrence with a current timestamp, then replacing all occurrences and then finally replacing timestamp with world
You can also use str.split('world')
and then join
var str = 'hello world hello world hello world hello';
var strs = str.split('world');
str = strs[0] + 'world' + strs.slice(1).join('');
console.log(str);
var str = 'hello world hello world hello world hello';
const d = Date.now()
str = str.replace('world', d).replace(/world/gi, '').replace(d, 'world');
console.log(str);
To provide an alternative to @Kristianmitk excellent answer, we can use a positive lookbehind, which is supported in Node.Js & Chrome >= 62
const string = 'hello world hello world hello world hello';
console.log(
string.replace(/(?<=world[\s\S]+)world/g, '')
);
// or
console.log(
string.replace(/(?<=(world)[\s\S]+)\1/g, '')
);
Using Symbol.replace well-known symbol.
The Symbol.replace well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the String.prototype.replace() method.
const string = 'hello world hello world hello world hello';
class ReplaceButFirst {
constructor(word, replace = '') {
this.count = 0;
this.replace = replace;
this.pattern = new RegExp(word, 'g');
}
[Symbol.replace](str) {
return str.replace(this.pattern, m => !this.count++ ? m : this.replace);
}
}
console.log(
string.replace(new ReplaceButFirst('world'))
);