I am trying to get a JavaScript code to select a string of text at random from an array. This is what I have so far but it doesn't seem to be working, appreciate the help. Don't know if this matters but this is for a website.
var myArray = ['One does not simply click the acorn'.'acorn spices all the rage with Martha Stewart', 'Once more into the acorn tree my friends','Acornbook launches as first acorn based social media'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var postmessage = + myArray;
You are using the dot "." instead of comma "," among the very first two elements in myArray.
You should use comma there as below.
var myArray = ['One does not simply click the acorn','acorn spices all the rage with Martha Stewart', 'Once more into the acorn tree my friends','Acornbook launches as first acorn based social media'];
You're getting the random value in the correct way, but the issue is what happens on line 3.
var postmessage = + myArray;
Putting a + sign in front of an array will try to turn it into a number, so doing + myArray results in NaN which is probably not what you wanted.
I'm going to guess that you probably wanted to store the random phrase in post message. Which would instead look like:
var postmessage = rand;
I think you made a simple mistake by accident. You are trying to add an array to a variable. I assume you wanted to add the randomly picked element so you would want on the third line:
var postmessage = + rand;
<script>
var postmessage = ''; // initialization for getting the random selected text from array
var myArray = ['One does not simply click the acorn', 'acorn spices all the rage with Martha Stewart', 'Once more into the acorn tree my friends', 'Acornbook launches as first acorn based social media'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var postmessage = rand;
</script>
Related
For a project I'm working on, I'm trying to make it so that when a button is pressed, an alert box pops up with a message. The message is randomly selected from an array.
I tried this already:
const rockTalk = [
'George is happy. Probably.',
'George is a bit parched, and would be most pleased if you provided him with a drink',
'George is going to sleep now.',
]
var randomItem = rockTalk[Math.floor(Math.random() * rockTalk.length)]
document.body.innerHTML = randomItem
var george = document.getElementById('georgeSprite')
function georgeSpeaks() {
alert('' + randomItem)
}
george.onclick = georgeSpeaks()
Your code is almost working. I have made a few changes so that it works.
The last comma in your rockTalk array adds 1 to the length of the array. In turn, this means that the random generator sometimes returns undefined.
var randomItem = rockTalk[Math.floor(Math.random() * rockTalk.length)] works fine, but you have placed it outside of the georgeSpeaks function. This means that it only runs once and so always produces the same message. I have placed it inside the function which corrects this.
document.body.innerHTML = randomItem doesn't do anything so I have removed it.
I have re-worked your code into a more conventional style.
Semi-colons are not required in JavaScript - they indicate the end of a statement - but they make code more readable.
This is your main mistake. Event handlers such as onclick require a function reference, which is the function name. Adding brackets executes the function, and in your case the returned value (undefined) is assigned to the event handler.
Your working code:
const rockTalk = [
'George is happy. Probably.',
'George is a bit parched, and would be most pleased if you provided him with a drink',
'George is going to sleep now.'
];
function georgeSpeaks() {
alert(rockTalk[Math.floor(Math.random() * rockTalk.length)]);
}
var george = document.getElementById('georgeSprite');
george.onclick = georgeSpeaks;
<button id='georgeSprite'>A rock</button>
I am trying to cut down and make my code simpler since my original method is not very readable and I get a lot of hard to understand errors for which I have to scan all of the code word by word as it is all one long line.
Lets say the text input was for
In my original code, I wrote :
//Example : You want to know if any of your favorite games were licensed by Nintendo
var tsf = (The value of a textInput in string form)
tsf.toLowerCase()
//Lets say the textinput said "Name your favorite games"
if(tsf.contains('mario') || tsf.contains('pokemon') || tsf.contains('mortal kombat')||etc,etc) {
Alert.alert('At least one of these games was licensed by Nintendo')
}
This works but in the real code there are a lot more "games" and it requires each and every item in the list as it is related to a health project I'm working on.
My 2nd idea was to create an array with all the elements and see if the array contains tsf
nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris',etc]
if(nintendoGames.contains(tsf)){
Alert.alert('This game was licensed by Nintendo')
}
This also works but only if tsf is a single word. Incase
tsf = 'mario, zelda'
the array method would not work since the array only contains 'mario' and 'zelda' and not the string 'mario, zelda'
I want to be able to scan to see if any part of the string contains any one of the elements in the array and so far, only the first solution works for me. If there is a modification in the .contains() function that works or if there is a certain script I have to write, it would be very useful. I wasn't able to find much online about this.
I am working on React.js with expo to host the app.
First, we convert the string to an array using 'split'.
Since we separate the games in the string with ', ' your code should be like:
tsf.split(', '); // we receive: ['mario','zelda'].
Then we use 'some' method to check if some of the elements in the array we created are in the 'nintedoGames' array.
const tsf = 'mario, zelda';
const nintendoGames = ['mario', 'pokemon', 'mortal kombat', 'zelda', 'tetris'];
const result = tsf.split(', ').some(game => nintendoGames.includes(game.toLowerCase()));
console.log(result)
let nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris'];
let str = "This is a mario games where you can play the way you like.";
if(nintendoGames.some(n => str.toLowerCase().includes(n.toLowerCase())))
alert("This game was licensed by Nintendo");
I'm trying to make a simple javascript command that I can run from the console in Chrome. I have a webpage which is filled with links that all follow the same format such as:
Example
This would take it to www.site/e/example.html
I want to be able to randomly pick on of them and follow the link. I've tried doing it using a regex but can't work out how to use it in the console. Any help here would be appreciated!
This is the simple expression I made (just extracts the "e/example" part):
$ <a href="(.+?).html">.+?<\/a>
You can use document.getElementsByTabName and select all a-elements on page. I guess, it is resilient way than regexp.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
First select all the links with querySelectorAll:
let links = document.querySelectorAll("a");
Then pick a random value, randomIndex returns an Integer between 0 and the array length.
let randomIndex = Math.floor(Math.random() * links.length);
let randomLink = links[randomIndex].href;
randomLink should now contain a randomly chosen link on the webpage.
What you can do is to list all a elements using document.querySelectorAll. You can then loop through them and extract their href property like so:
const links = [...document.querySelectorAll("a")].map(x => x.href);
Then just select a random element from this array:
const link = links[Math.floor(Math.random() * links.length)];
I want to change the content of a div randomly by .InnerHTML. The text are saved as variables. The random number is another variable. The Problem is, that if I put text and random number together it will print text1 for example.
Can someone help me with that?
function switchText(){
var text1 = "hello";
var text2 = "there";
var text3 = "ObiWan";
var randomNumber = Math.floor(Math.random() * 3) + 1;//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = "text" + randomNumber;
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
How about storing all random strings in an array, like so:
function switchText(){
var randomWords = ["hello", "there", "ObiWan"];
var randomIndex = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = randomWords[randomIndex];
//the problem
}
Actually you can access those variables by using index notation (it's described really nicely here) so in your specific case of function you just need to change the line where you try to access the variable to
document.getElementById("randomText").innerHTML = this['text' + randomNumber];
However though such notation is not something I would recommend. Usage of array as it was suggested is much more readable in fact.
Store those texts into an array and use the random number.
Get the random number as follow: Math.floor(Math.random() * 3)
function switchText(){
var texts = ["hello", "there", "ObiWan"];
var randomNumber = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[randomNumber];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
You can store those texts into an object as well.
function switchText() {
var texts = {
"text1": "hello",
"text2": "there",
"text3": "ObiWan"
};
var randomNumber = Math.floor(Math.random() * 3) + 1; //creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[`text${randomNumber}`];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Your question is focused on how to dynamically construct a variable name, but usually this problem comes up because the solution you are attempting is based on a coding pattern that has boxed you into a corner. Instead of writing a potentially hazardous solution or one that is overly complex, re-think your approach.
Whenever you have several pieces of data to store that don't have key names to go with them, you should be storing those data in an Array. The advantages to storing data in an array are huge. So, you should place the strings into an array instead of individual variables that all have to have similar names. So, now you have less variables to worry about and no variable names that have to be set to certain values and the problem of dynamically creating a variable name is gone entirely.
All you need to do now is to use the random number as an index to the array. Don't adjust the random to make it 1-based, because arrays are 0-based. And, when you get the random, multiply it by the length of the array, rather than hard code a number. This way, all you have to do is add/remove strings to the array for them to become possible resulting strings.
This structure and solution make your code simpler and more flexible.
Also, don't set up your event handlers using HTML event attributes. There are many reasons why you shouldn't use this 25+ year old technique. Do it in JavaScript.
var strings = ["hello","there","ObiWan"]; // Store the possible strings in an array
var btn = document.getElementById("randomText"); // Get a reference to the trigger element
var output = document.getElementById("output"); // And the output area
// Set up the event handler in JavaScript, not HTML
btn.addEventListener("click", function(){
// Set the output to a string from the array using a random index
output.innerHTML = strings[Math.floor(Math.random() * strings.length)];
});
<button id="randomText">click here</button>
<div id="output"></div>
So lets say I have a mailto email in which a checkbox question exists that asks the user to pick the best fruits out of a list of fruits (check all that apply.) They end up with apples, bananas, and pears. The mailto email that they trigger then contains the following (assuming the checkboxes in the question are named bestFruits):
...
bestFruits=apples
bestFruits=bananas
bestFruits=pears
...
So in my javascript file, I have the following line to parse values from the email:
var bestFruits = mail.bodyText.match(/bestFruits=\s*(\S.*\S)\s*/);
So my issue is that this would (presumably) take only one value by the end. What I need, is for the javascript to loop and add each value of bestFruits in the email to the bestFruits var so that each value (apples, bananas, and pears) are all in the bestFruits var.
Is there any way to do this? I tried making a for loop, but I couldn't determine the syntax to loop through the mailto email body and add each instance of bestFruits to the variable.
I'm still extremely new to all this, as I was thrust in recently. If I'm missing something fundamental, I'd appreciate a quick pointing-out. If you require any more info, I'd be happy to try to provide it.
Thanks for reading guys!
You don't need looping. You do need to match all the fruits (as per your example, matching all single words after bestFruits), remove bestFruits= from the matches, join the resulting array and store it in a variable. Like this:
var bestFruits = mail.bodyText.match(/bestFruits=\w+/g)
.map(function(x){return x.split('=')[1]})
.join(',');
What does it do:
Matches all your best fruits.
Takes each bestFruits=abc element and replaces it with abc (i.e., splits with = separator and takes the second part)
Makes the string of your fruits (converts the resulting array to string with , joiner).
You were very close - modified your regex a little bit:
var body = `this=is
an=example
bestFruits=apples
bestFruits=bananas
bestFruits=pears
of=doing
things=ok?
`;
var re = /bestFruits=(.*)/g;
var fruitMatches = body.match(re);
var bestFruits = fruitMatches.map(function(fruitMatch) {
return fruitMatch.split('=')[1];
});
console.log(bestFruits); // ["apples", "bananas", "pears"]
Fiddle