1

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?

Michiel van Dijk
  • 783
  • 2
  • 8
  • 19
  • 2
    What about using a loop? – evolutionxbox Feb 09 '21 at 16:57
  • That's what I was thinking about as well. Unfortunately my JS knowledge stops with the straightforward functions, and hangs me out to dry with more complex things such as loops and arrays etc – Michiel van Dijk Feb 09 '21 at 16:58
  • 1
    Does this answer your question? [How to replace all occurrences of a string in Javascript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – evolutionxbox Feb 09 '21 at 17:01
  • Unfortunately not. That solution would replace every occurrence, where I'm looking to replace one occurrence a certain number of times (based on var) – Michiel van Dijk Feb 09 '21 at 17:05
  • @evolutionxbox this is not the case the article you reference is about **all occurences** and not a specific amount of occurences – Aalexander Feb 09 '21 at 17:06

2 Answers2

1

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);
Aalexander
  • 4,987
  • 3
  • 11
  • 34
1

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));
Siva K V
  • 10,561
  • 2
  • 16
  • 29