I am struggling with generating strings in JavaScript. Specifically, I have an array of numbers from which a string needs to be generated. The string must contain at least 1 number from the array, but must not contain a specific number given by the user. Additionally, the string length must be exactly 7 digits long.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
My current approach involves randomly selecting a number from the array, then choosing a random position in the string, and finally filling in the remaining digits with random numbers. However, I keep encountering issues where the process takes too long or causes my browser to freeze, especially when checking for the excluded number.
//randomly select a number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//randomly determine position of the selected number
var position = Math.floor(Math.random() * 6);
//calculate length of string after the selected number
var afterlen = 7 - (position+2);
//genNum(...) is a function I use to generate a string of numbers with a specific length
var nstr = genNum(position) + getRandom + genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position) + getRandom + genNum(afterlen);
}
I am looking for ways to optimize this process and prevent long loading times or browser freezes. Any suggestions on how to improve this would be greatly appreciated.
Update: This task is part of my homework assignment related to generating phone numbers. The final string format should resemble something like "37915002".