Ricko Abbderahamne
Ricko Abbderahamne

Reputation: 43

Function in js or jquery to replace "X" with a random number

example:

var = "10XX489X1X2"

the function must replace X with a random number (example) : 10(50)4895(1)(9)2

All numbers must be different

Upvotes: 0

Views: 126

Answers (2)

DecPK
DecPK

Reputation: 25408

You can replace All occurrences of X with a random number (I've taken the range from 1 to 99). You can do this with the help of replaceAll

var s = "10XX489X1X2";

function randomIntFromInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

const str = s.replaceAll("X", () => randomIntFromInterval(1, 99));

const num = Number(str);
console.log(num);

using for..of loop

var s = "10XX489X1X2";

function randomIntFromInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

let strArr = [];
for (let char of s) {
  if (char === "X") strArr.push(randomIntFromInterval(1, 99));
  else strArr.push(char);
}

const resultStr = strArr.join("");
console.log(resultStr);

Upvotes: 1

Proximitynow
Proximitynow

Reputation: 64

I think this solution should work. It will replace every time there is a 'X' in the original string with the same random number. After that, it will convert the string into a number then print the result.

const min = 0;
const max = 9;

let originalNumber = "10XX489X1X2";

originalNumber = Number(originalNumber.replace(/X/g, Math.round(Math.random() * (max - min) + min)))

console.log(originalNumber)

Upvotes: 0

Related Questions