Random 'email format' text using jQuery - javascript

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

Related

How can I randomly capitalise letters in a string

I'm sorry if this has been asked before, but I can't seem to find the right answer.
I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:
Must contain letters, numbers and special characters
Must be 14 characters
Must have upper and lower case lettering
Must log the result as a string
Here is what I have:
var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;
function randomPassword() {
for (i=0; i<=13; i++) {
var mix = characters.charAt(Math.floor(Math.random() * length));
var newString = results += mix;
}
console.log(newString);
}
randomPassword();
The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.
This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)
Thanks!
Here's one way
myString.toLowerCase().split('').map(function(c){
return Math.random() < .5? c : c.toUpperCase();
}).join('');
your code is good and correct just make a simple improvement as mentioned below. you can achieve your goal.
var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;
function randomPassword() {
var check = 2;
for (i=0; i<=13; i++) {
var mix = characters.charAt(Math.floor(Math.random() * length));
if (mix.match(/[a-z]/i) && check>0) {
mix = mix.toUpperCase();
check --;
}
var newString = results += mix;
}
console.log(newString);
}
randomPassword();
var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;
function randomPassword() {
var check = 2;
for (i=0; i<=13; i++) {
var mix = characters.charAt(Math.floor(Math.random() * length));
if (mix.match(/[a-z]/i) && check>0) {
mix = mix.toUpperCase();
check --;
}
var newString = results += mix;
}
console.log(newString);
}
randomPassword();
if you need to have both upper and lower characters and numbers and special chars, a random choice from a single characters variable can't always ensure this requirement.
In the version below I've created an array of characters subsets, where every required subset is included at least 3 times in the final password.
Simple version
var alphabet = [
'abcdefghijklmnoqrstuvwxyz',
'ABCDEFGHIJKLMNOQRSTUVWXYZ',
'0123456789',
'?<>!"£$%^&*()-+./'
];
password = '';
for (var i = 0; i < 14; i++) {
var subset = alphabet[i%4];
password += subset[Math.floor(Math.random() * subset.length)]
}
console.log(password);
Safer version
here both the subsets and the password are scrambled using a JS implementation of Fisher-Yates algorithm so to avoid predictable generations.
function shuffle_Fisher_Yates(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var alphabet = shuffle_Fisher_Yates([
'abcdefghijklmnoqrstuvwxyz',
'ABCDEFGHIJKLMNOQRSTUVWXYZ',
'0123456789',
'?<>!"£$%^&*()-+./'
]);
password = '';
for (var i = 0; i < 14; i++) {
var subset = alphabet[i%4];
password += subset[Math.floor(Math.random() * subset.length)]
}
console.log(shuffle_Fisher_Yates(password.split('')).join(''));
It's my way to capitalise some random characters from a given string.
const myString = 'manoj_rana';
const randomCapitaliseString = [...myString].map(c => Math.random() < .6 ? c : c.toUpperCase()).join('');

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

How can I make my output appear all on one line with no spaces?

I have a simple Javascript problem that I'm working on, where the point is to...
Take an input, like 123
Separate the input as single digits, then square those single digits, thus getting 149.
Display that "149" (in this case) as an output.
I don't know how to display it as 149. I can only show it as
1
4
9
Sure, I might try adding it to an array then for looping the results... something tells me that this is the slow solution, and that there is a faster one. Here's my code.
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
console.log(newnum);
}
}
squareDigits(123);
Create empty array outside of the loop
Add squares of the each digit in the array
Join the array after loop finishes
function squareDigits(num) {
num = '' + num;
var len = num.length;
var squares = []; // Define empty array
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
squares.push(Math.pow(digit, 2)); // Push the square of the digit at the end of array
}
return squares.join(''); // Join the array elements with empty string as glue
}
var squares = squareDigits(123);
console.log(squares);
document.write(squares);
By string concatenation
Declare a empty string before the for loop
Concatenate the square of the digit to the string by first casting the number to string
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum = ''; // Decalare variable with Empty string
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum += '' + Math.pow(digit, 2); // Cast the square to string and then concatenate to the string
}
return newnum; // Return the string
}
var squares = squareDigits(123);
document.write(squares);
Try utilizing String.prototype.split() , Array.prototype.map() , Array.prototype.join()
function squareDigits(num) {
return String(num).split("")
.map(function(n) {
return Math.pow(n, 2);
}).join("");
}
console.log(squareDigits(123));
What about this?
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
var digits = '';
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
digits += '' + newnum
}
console.log(digits);
}
try process.stdout.write, as in
process.stdout.write(newnum);

Take random letters out from a string

I want to remove 3 RANDOM letters from a string.
I can use something like substr() or slice() function but it won't let me take the random letters out.
Here is the demo of what I have right now.
http://jsfiddle.net/euuhyfr4/
Any help would be appreciated!
var str = "hello world";
for(var i = 0; i < 3; i++) {
str = removeRandomLetter(str);
}
alert(str);
function removeRandomLetter(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos)+str.substring(pos+1);
}
If you want to replace 3 random charc with other random chars, you can use 3 times this function:
function substitute(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos) + getRandomLetter() + str.substring(pos+1);
}
function getRandomLetter() {
var letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var pos = Math.floor(Math.random()*letters.length);
return letters.charAt(pos);
}
You can split the string to an array, splice random items, and join back to a string:
var arr = str.split('');
for(var i=0; i<3; ++i)
arr.splice(Math.floor(Math.random() * arr.length), 1);
str = arr.join('');
var str = "cat123",
amountLetters = 3,
randomString = "";
for(var i=0; i < amountLetters; i++) {
randomString += str.substr(Math.floor(Math.random()*str.length), 1);
}
alert(randomString);
fiddle:
http://jsfiddle.net/euuhyfr4/7/
This answer states that
It is faster to slice the string twice [...] than using a split followed by a join [...]
Therefore, while Oriol's answer works perfectly fine, I believe a faster implementation would be:
function removeRandom(str, amount)
{
for(var i = 0; i < amount; i++)
{
var max = str.length - 1;
var pos = Math.round(Math.random() * max);
str = str.slice(0, pos) + str.slice(pos + 1);
}
return str;
}
See also this fiddle.
you can shuffle characters in your string then remove first 3 characters
var str = 'congratulations';
String.prototype.removeItems = function (num) {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("").substring(num);
}
alert(str.removeItems(3));
You can use split method without any args.
This would return all chars as a array.
Then you can use any randomiser function as described in Generating random whole numbers in JavaScript in a specific range? , then use that position to get the character at that position.
Have a look # my implementation here
var str = "cat123";
var strArray = str.split("");
function getRandomizer(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
alert("Total length " + strArray.length);
var nrand = getRandomizer(1, strArray.length);
alert("Randon number between range 1 - length of string " + nrand);
alert("Character # random position " + strArray[nrand]);
Code # here https://jsfiddle.net/1ryjedq6/

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