How to add a common string in every randomly generated string Javascript - 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.

A rough sketch of the algorithm is this:
create random string of length size - <FIXED_STRING>.length
append <FIXED_STRING> to the end of generated string
Done.
A corner case is if size < <FIXED_STRING>.length, here you would need to provide some more discussion on what should happen.

You can use String.prototype.slice() to select 0-n characters from possible to insert into random index within string returned from randomTextArrayGeneration. If 0 is passed to randomTextArrayGeneration the selected string from possible will be set as result
var randomTextArrayGeneration = function(size, from, to) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < size; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
};
var len = Math.floor(Math.random() * text.length - 3);
var res = text.slice(0, len) + possible.slice(from, to).toLowerCase() + text.slice(len);
return res
}

Related

Adding style tags around specific characters only

I am trying to add inline styling to only numbers in paragraph elements. For example:
<p>This paragraph has the numbers 1 and 2 in it.</p>
So in this instance, I would want to put <span class="style">1</span>and <span class="style">2</span>. Around the two numbers in that paragraph.
I am trying to write a javascript to accomplish this so I don't have to go back into the document I'm working on and manually add the styling tags around each number, as the document is very long.
So far this is what I wrote, but I'm having difficulty figuring out what to do for the next step on how to incorporate the edits back into the paragraph HTML.
let regEx=/[0-9]/g;
let list = [];
let paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
let html = paragraphs[i].innerHTML;
list.push(html);
}
// all paragraphs into one string.
let joined = list.join(' ');
// all the numbers in the paragraphs stored in array
let numbers = joined.match(regEx);
// define array for styling edits
let edits = [];
// adding the styling tags to each num
numbers.forEach(function(num){
edits.push('<span class="style">' + num + '</span>');
// outputs ["<span class='style'>3</span>", "<span class='style'>7</span>", "<span class='style'>4</span>", "<span class='style'>5</span>"]
});
// need to insert edits into paragraph html
If anyone can offer any suggestions on how I might be able to accomplish this that would be great, I am still relatively new to working with JS.
const paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
const regEx=/([0-9])/g;
const newHtml = paragraphs[i].innerHTML.replace(regEx, '<span class="style">$1</span>');
paragraphs[i].innerHTML = newHtml;
}
I updated your regex to put the number in a group, then in the string replace you can reference that group, since there is only one it will be $1. As you can see in the replace we are wrapping that with the appropriate span and then plugging it right back into the innerHTML.
I did notice that your regex is only capturing single digit numbers, if you wanted to capture multi-digit numbers, you could update your reg ex like this: /([0-9]+)/g.
I created a simple jsfiddle to show you how it works: https://jsfiddle.net/andyorahoske/dd6k6ekp/35/
I broke out the most fundamental part of this into a reusable function that you may find helpful in other contexts.
/**
* Wraps numbers in a string with any provided wrapper.
* #param {String} str A string containing numbers to be wrapped.
* #param {String} wrapper A string with placeholder %s to define the wrapper. Example - <pre>%s</pre>
* #return {String} The original string with numbers wrapped using the wrapper param.
*/
function wrapNumbers(str, wrapper) {
var numbersInStr = str.match(/\d+/g) || [];
var chunks = [];
var segmentStart = 0;
for(var i = 0; i < numbersInStr.length; i += 1) {
var number = numbersInStr[i];
var indexOfNumber = str.indexOf(number);
var fWrapper = wrapper.replace('%s', number);
chunks.push(str.slice(segmentStart, indexOfNumber));
chunks.push(fWrapper);
segmentStart = indexOfNumber + number.length;
}
if(segmentStart < str.length) {
chunks.push(str.slice(segmentStart, str.length));
}
return chunks.join('');
}
To use this in your use case it might look like the following:
var paragraphs = document.getElementsByTagName("p");
var wrapper = '<span class="style">%s</span>';
for(var i = 0; i < paragraphs.length; i += 1) {
var paragraph = paragraphs[i];
paragraph.innerHTML = wrapNumbers(paragraph.innerHTML, wrapper);
}
Codepen: https://codepen.io/bryceewatson/pen/vRqeVy?editors=1111
Here's a new code https://jsfiddle.net/fazanaka/au4jufrr/1/
var element = document.getElementById('text'),
text = element.innerText,
wordsArray = text.split(' '),
newString;
for(var i = 0; i < wordsArray.length; i++){
if(!isNaN(parseFloat(wordsArray[i])) && isFinite(wordsArray[i])){
wordsArray[i] = "<span class='style'>" + wordsArray[i] + "</span>";
}
}
newString = wordsArray.join(' ');
element.innerHTML = newString;
I hope it helps you
UPD:
For all paragraphs https://jsfiddle.net/fazanaka/qx2ehym4/

How to create random string in Javascript? [duplicate]

This question already has answers here:
javascript password generator
(34 answers)
Generate random string/characters in JavaScript
(93 answers)
Closed 5 years ago.
I would like to create random strings. But I am not get a right way. any one can help me please?
my try :
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
console.log( Math.random( charset ) * anysize ); //getting bad result
Is it possible to correct me? or any other elegant way to fix this?
Thanks in advance.
You should use .length property of your string of possible characters(charset).
Also, use Math.floor method in order to get integer positions of your chars array.
You can get a random item from charset string using its array index:
charset[Math.floor(Math.random() * charset.length)]
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
result="";
for( var i=0; i < anysize; i++ )
result += charset[Math.floor(Math.random() * charset.length)];
console.log(result);
function randomString(anysize, charset) {
var res = '';
while (anysize--) res += charset[Math.random() * charset.length | 0];
return res;
}
Something like that
You could get the n-index char of string charset and append to a new string many times as you need, see following please:
var anysize = 3;//the size of string
var charset = "abcdefghijklmnopqrstuvwxyz"; //from where to create
var i=0, ret='';
while(i++<anysize)
ret += charset.charAt(Math.random() * charset.length)
console.log(ret);
The first thing you will want to do is create a helper function that can grab a random value from an array.
getRandomValue(array) {
const min = 0; // an integer
const max = array.length; // guaranteed to be an integer
/*
Math.random() will return a random number [0, 1) Notice here that it does not include 1 itself
So basically it is from 0 to .9999999999999999
We multiply this random number by the difference between max and min (max - min). Here our min is always 0.
so now we are basically getting a value from 0 to just less than array.length
BUT we then call Math.floor on this function which returns the given number rounded down to the nearest integer
So Math.floor(Math.random() * (max - min)) returns 0 to array.length - 1
This gives us a random index in the array
*/
const randomIndex = Math.floor(Math.random() * (max - min)) + min;
// then we grab the item that is located at that random index and return it
return array[randomIndex];
}
You could use this helper function with no regard for changing the length of the string, like this:
var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);
However, you may want to create another function that contains a loop based on how long you want the random string to be:
function getRandomString(charset, length) {
var result = '';
for (var i = 0; i <= length; i++) {
result += getRandomValue(charset);
}
return result;
}
And that function would be used like this
var randomString = getRandomString(charset, 3);

How to build a binary-array from hex strings

I'm new to the concept of working with data on the binary level and am hoping someone can give me a hand here...
I'd like to build a binary buffer out of a series of hex numbers that are represented as strings.
For example,
suppose I have "xFCx40xFF" and I want to turn this into an array that looks like: 111111000100000011111111.
What's the best way to do this?
My best attempt seems to not be working:
var raw = "xFCx40xFF"
var end = raw.length-2;
var i = 1;
var j = 0;
var myArray = new Uint8Array(raw.len);
while (i < end) {
var s = raw.substr(i,2);
var num = parseInt(s,16);
i += 3;
myArray[j] = num;
j += 8;
}
Each 3 characters in string will represent 1 number in Uint8Array. Each number in Uint8Array will represent 8 bits. Your code was creating Uint8Array larger than needed and then placing values are wrong locations.
I have simplified the code to use a singe index i which represents the location in the Uint8Array. Corresponding location in string can be easily computed from i.
var raw = "xFCx40xFF"
var myArray = new Uint8Array(raw.length / 3);
for (var i = 0; i < raw.length / 3; i++) {
var str = raw.substr(3 * i + 1, 2);
var num = parseInt(str, 16);
myArray[i] = num;
}
Remove the 'x' character of your hex string and call parseInt() with the radix 16 and toString() with the radix 2 to get the binary string.
var raw = "xFCx40xFF";
var bin = parseInt(raw.split('x').join(''), 16).toString(2);
document.body.textContent = bin;
and if you need an array, just add .split('') at the end.
parseInt(raw.split('x').join(''), 16).toString(2).split('');
or iterate through each character.

Random 'email format' text using jQuery

I want to know how I can get a random text variable in jQuery like this format:
gwtq3tw3232dsk#domain.com
15 digit random combination of letters and numbers in the first part and '#domain.com' in the second part which remains the same.
I want to get real random entries that are different all the time.
how to do this with javascript or jquery?
Thanks
Use chancejs github
email
chance.email()
chance.email({domain: "example.com"})
Return a random email with a random domain.
chance.email()
=> 'kawip#piklojzob.gov'
Optionally specify a domain and the email will be random but the domain will not.
chance.email({domain: 'example.com')
=> 'giigjom#example.com'
Or pure JavaScript
fiddle DEMO
function makeEmail() {
var strValues = "abcdefg12345";
var strEmail = "";
var strTmp;
for (var i = 0; i < 10; i++) {
strTmp = strValues.charAt(Math.round(strValues.length * Math.random()));
strEmail = strEmail + strTmp;
}
strTmp = "";
strEmail = strEmail + "#";
for (var j = 0; j < 8; j++) {
strTmp = strValues.charAt(Math.round(strValues.length * Math.random()));
strEmail = strEmail + strTmp;
}
strEmail = strEmail + ".com"
return strEmail;
}
console.log(makeEmail());
var chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
var string = '';
for(var ii=0; ii<15; ii++){
string += chars[Math.floor(Math.random() * chars.length)];
}
alert(string + '#domain.com');
This will randomly pick characters to add to the email string.
Note that this might, once in a blue moon, generate duplicates. In order to completely eliminate duplicates, you would have to store all generated strings and check to make sure that the one you are generating is unique.
JSFiddle Demo.
Using the answers from generate a string of 5 random characters
function getRandomEmail(domain,length)
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text + domain;
}
var email = getRandomEmail("#domain.com",15);
Lets do the trick with toSting to generate alphanumeric string
return Math.random().toString(36).substring(2,11) + '#domain.com';
shortest as possible
If you like to have first character a letter, it could be combination with selection of the first character from the character list
var chars = 'abcdefghijklmnopqrstuvwxyz';
return chars[Math.floor(Math.random()*26)] + Math.random().toString(36).substring(2,11) + '#domain.com';

Generate random letters in javascript and count how many times each letter has occurred?

I want to generate a string of random letters say 10 letters from a-z one after the other i.e. the next letter should be displayed after the previous letter after a certain delay, later, I want to calculate the number of times each letter has been generated, unlike what I have done previously, i.e. I have taken a predefined array of letters and generated them accordingly.
Shorter way to generate such a string using String.fromCharCode:
for (var i = 0, letter; i < 10; i++) {
setTimeout(function() {
letter = String.fromCharCode(97 + Math.floor(Math.random() * 26));
out.appendChild(document.createTextNode(letter)); // append somewhere
}, 2000 * i);
}
And complete demo covering all the problems in this question: http://jsfiddle.net/p8Pjq/
Use the setInterval method to run code at an interval. Set up an array for counting each character from the start, then you can count them when you create them instead of afterwards:
var text = '';
var chars = 'abcdefghijklmnopqrstuvwxyz';
var cnt = new Array(chars.length);
for (var i = 0; i < cnt.length; i++) cnt[i] = 0;
var handle = window.setInterval(function(){
var ch = Math.floor(Math.random() * chars.length);
cnt[ch]++;
text += chars.charAt(ch);
$('#display').text(text);
if (text.length == 20) {
window.clearInterval(handle);
// now all characrers are created and counted
}
}, 2000);
Demo: http://jsfiddle.net/R8rDH/
I am stealing this answer, but look here: Generate random string/characters in JavaScript
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}

Categories

Resources