Reputation: 963
I've looked across the forum but couldn't find a solution to my question.
I'd like to perform a pretty straightforward replace(). However, where I get stuck is that I want to replace Microsoft with W3Schools n times, based on a variable value that I'll be adding to the JS script (let's call it 'var').
var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools");
Does anyone know how to set that up?
Upvotes: 1
Views: 90
Reputation: 5004
You can use a loop here. In the snippet below a for-loop, define your const n which indicates how often the replace function will be applied. Inside the loop's body call the replace function, update your string in each iteration with the result of the replace function. Means in each iteration the next occurence of your search word.
const n = 5;
for (let i = 0; i < n; i++) {
str = str.replace("Microsoft", "W3Schools");
}
var str = "Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!Visit Microsoft!";
const n = 5;
for (let i = 0; i < n; i++) {
str = str.replace("Microsoft", "W3Schools");
}
console.log(str);
Upvotes: 1
Reputation: 11001
Use reduce
var str = "Visit Microsoft! Visit Microsoft! Visit Microsoft!";
const replace = (n) =>
Array(n)
.fill(0)
.reduce((str, cur) => str.replace("Microsoft", "W3Schools"), str);
console.log(replace(2));
Upvotes: 1