Dominicentek Gaming
Dominicentek Gaming

Reputation: 127

Replace random substring in JavaScript

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

Upvotes: 2

Views: 107

Answers (1)

Alexander B.
Alexander B.

Reputation: 26

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

Upvotes: 1

Related Questions