2

I am trying to replace random substring with another within a string. This is my code

function replaceRandomSubstring(str, substr, repl) {
  var amount = str.match(substr)
  var newstr = str;
  if (amount.length != -1) {
    var index = Math.floor(Math.random() * amount.length)
    var i = 0;
    do {
      if (i == index) newstr = newstr.replace(substr, repl)
      else newstr = newstr.replace(substr, "placeholder")
      i++;
    }
    while (i < index)
    newstr = newstr.split("placeholder").join(substr)
  }
  return newstr;
}

What's happening is that it replaces the very first substring not random one

4
  • Can you show an example of the values you're passing to the function. Commented Aug 9, 2020 at 8:11
  • @Teemu replaceRandomSubstring(teststring, "test", "replacement") and teststring contains: "test, test, test, test, test" Commented Aug 9, 2020 at 8:16
  • OK, and you want to replace a single substr only, not a random amount of the occurrences? Commented Aug 9, 2020 at 8:23
  • a single substring Commented Aug 9, 2020 at 8:39

1 Answer 1

1

This is because amount doesn't return all matches of the substrings. It returns the first match.

Use String.prototype.matchAll() instead:

function replaceRandomSubstring(str, substr, repl) {
  const amount = [...str.matchAll(substr)]; // collect all substring matches into one array

  if (amount.length !== -1) {
    const index = Math.floor(Math.random() * amount.length);

    let i = 0;

    do {
      if (i === index) str = str.replace(substr, repl);
      else str = str.replace(substr, 'placeholder');
      i++;
    } while (i <= index);

    str = str.split('placeholder').join(substr);
  }
  return str;
}
Sign up to request clarification or add additional context in comments.

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.