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?

5
  • 2
    What about using a loop? Commented Feb 9, 2021 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 Commented Feb 9, 2021 at 16:58
  • 1
    Does this answer your question? How to replace all occurrences of a string in Javascript? Commented Feb 9, 2021 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) Commented Feb 9, 2021 at 17:05
  • @evolutionxbox this is not the case the article you reference is about all occurences and not a specific amount of occurences Commented Feb 9, 2021 at 17:06

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.