Dazzler Dazzler - 1 year ago 47
Node.js Question

How to add a common string in every randomly generated string Javascript

I am generating random strings using the below function in node.js. I wanted to know if there is any way to create text strings appropriately with a common string within every randomly generated string.

EDIT: The common string can be in any location of the generated string

For example:

Randomly generated string - Cxqtooxyy4

Can I add 'abc' or 'ABC' within that string like this - Cxqtoabcoxyy4 or CxqtoABCoxyy4 respectively.

My Code -

var randomTextArrayGeneration = function(size)
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0;i<size;i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;

Can anyone tell me how do I do this? Any help is really helpful.

var n = text.length; //The size of your random string
var randomPosition = Math.floor((Math.random() * n) + 1); //Generate a  random number between 1 and the size of your string

//Separate your string in 2 strings
var text1 = text.substring(1, randomPosition); 
var text2 = text.substring(randomPosition, n); 

//Create your final string by adding the common string between your two halves
var textFinal = text1 + commonString + text2;

return textFinal;

I don't remember how exactly works .substring(), you may want to change 1 by 0 in some places.