Dynamically Find Values from a Variable - javascript

let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
const storyWords = story.split(" ");
//console.log(storywords.length);
let overusedWords = ['really', 'very', 'basically'];
let WoolReally = 0;
let WoolVery = 0;
let WoolBasically = 0;
for(x of storyWords) {
if (x === 'really'){
WoolReally++;
}
else if (x === 'very'){
WoolVery++;
}
else if (x === 'basically'){
WoolBasically ++;
}
}
console.log("Really was counted " + WoolReally + " times.");
console.log("Very was counted " + WoolVery + " times.");
console.log("Basically was counted " + WoolBasically + " times.");
Please can you help me try figure out how to dynamically check if a sentence includes any values that another variable includes and count that value.
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
const storyWords = story.split(" ");
//console.log(storywords.length);
let overusedWords = ['really', 'very', 'basically'];
let WoolReally = 0;
let WoolVery = 0;
let WoolBasically = 0;
for(x of storyWords) {
if (x === 'really'){
WoolReally++;
}
else if (x === 'very'){
WoolVery++;
}
else if (x === 'basically'){
WoolBasically ++;
}
}
console.log("Really was counted " + WoolReally + " times.");
console.log("Very was counted " + WoolVery + " times.");
console.log("Basically was counted " + WoolBasically + " times.");
You can see that I have had to create a singular variable for each of the words that are part of the string for variable - overUsedWords in order to be able to count them in the loop and if else statement. There must be a way to beaten this up so I don't have to do it with
let WoolReally = 0;
let WoolVery = 0;
let WoolBasically = 0;
Let me know what you think. I do apologise if this is super simple stuff. I'm just learning

can create a counts object from the overusedWords array using array reduce
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
const storyWords = story.split(" ");
let overusedWords = ['really', 'very', 'basically'];
let counts = overusedWords.reduce((acc,curr) => {
acc[curr] = storyWords.filter(x => x===curr).length;
return acc;
},{})
console.log(counts)
console.log(counts['very'])
console.log(counts['really'])

let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
const storyWords = story.split(" ");
let overusedWords = ['really', 'very', 'basically'];
for(let word of overusedWords){
let wordCount = storyWords.filter((storyWord) => {return storyWord === word;}).length
console.log("The word '"+word+"' has been used "+wordCount+ " times" );
}
In this way you are simply filtering the list of the word obtained by the splitting of the story for each of the word inside your overusedWord list and returning the count of them. In this way if you want to add further words you just have to add them into your 'overusedWord' array and it will continue to work.

Create an object with three properties:
const obj = {
WoolReally: 0,
WoolVery: 0,
WoolBasically: 0
}
Update the object in the loop
for(x of storyWords) {
if (x === 'really'){
obj.WoolReally += 1
}
else if (x === 'very'){
obj.WoolVery += 1;
}
else if (x === 'basically'){
obj.WoolBasically += 1;
}
}
for(let i in obj){
console.log(`${i} has been counted ${obj.i} times`);
}

Related

Understand the following exercise of js loops and strings in array

I'm trying to make sense of the following javascript exercise but can't seem to make sense of it, all I know for now is that I can access each string with "acrostic[i]" where the i would be the number in the array but don't know where to go from there.
const acrostic = [
"Give me your patience, sister, while I frame",
"Exact in capitals your golden name;",,
"Or sue the fair Apollo and he will",
"Rouse from his heavy slumber and instill",
"Great love in me for thee and Poesy.",
"Imagine not that greatest mastery",
"And kingdom over all the Realms of verse,",
"Nears more to heaven in aught, than when we nurse",
"And surety give to love and Brotherhood.",
" ",
"Anthropophagi in Othello's mood;",
"Ulysses storm'd and his enchanted belt",
"Glow with the Muse, but they are never felt",
"Unbosom'd so and so eternal made,",
"Such tender incense in their laurel shade",
"To all the regent sisters of the Nine",
"As this poor offering to you, sister mine.",
" ",
"Kind sister! aye, this third name says you are;",
"Enchanted has it been the Lord knows where;",
"And may it taste to you like good old wine,",
"Take you to real happiness and give",
"Sons, daughters and a home like honied hive."
];
/* Declare a variable that will return the final string */
let georgianaAugustaKeats = "acrostic[i][0]";
for (let i = 0; i < acrostic.length; i += 1) {
/* add each first character of each string to the array
to the georgianaAugustaKeats variable*/
}
console.log(georgianaAugustaKeats);
While the other answers are correct, I think they're not beginner-friendly.
If all you need to do for the exercise is to replace the part commented in the for loop, then it's simply:
let georgianaAugustaKeats = "";
for (let i = 0; i < acrostic.length; i += 1) {
georgianaAugustaKeats += acrostic[i][0];
}
console.log(georgianaAugustaKeats);
NOTE: The third string ends with an empty ,,, I'm not sure that's intentional. That will cause this code to generate an error (because the string is empty, there's no first element). You can easily account for that, but I think it's another question.
You can use map() with some destructuring to generate an array containing the first letter of every line, and then join() that array into a string:
const acrostic = [
"Give me your patience, sister, while I frame",
"Exact in capitals your golden name;",
"Or sue the fair Apollo and he will",
"Rouse from his heavy slumber and instill",
"Great love in me for thee and Poesy.",
"Imagine not that greatest mastery",
"And kingdom over all the Realms of verse,",
"Nears more to heaven in aught, than when we nurse",
"And surety give to love and Brotherhood.",
" ",
"Anthropophagi in Othello's mood;",
"Ulysses storm'd and his enchanted belt",
"Glow with the Muse, but they are never felt",
"Unbosom'd so and so eternal made,",
"Such tender incense in their laurel shade",
"To all the regent sisters of the Nine",
"As this poor offering to you, sister mine.",
" ",
"Kind sister! aye, this third name says you are;",
"Enchanted has it been the Lord knows where;",
"And may it taste to you like good old wine,",
"Take you to real happiness and give",
"Sons, daughters and a home like honied hive."
];
const result = acrostic.map(([first]) => first).join('');
console.log(result);
You can use Array.prototype.reduce() combined with Destructuring assignment
Code:
const acrostic = [
'Give me your patience, sister, while I frame',
'Exact in capitals your golden name;',
,
'Or sue the fair Apollo and he will',
'Rouse from his heavy slumber and instill',
'Great love in me for thee and Poesy.',
'Imagine not that greatest mastery',
'And kingdom over all the Realms of verse,',
'Nears more to heaven in aught, than when we nurse',
'And surety give to love and Brotherhood.',
' ',
"Anthropophagi in Othello's mood;",
"Ulysses storm'd and his enchanted belt",
'Glow with the Muse, but they are never felt',
"Unbosom'd so and so eternal made,",
'Such tender incense in their laurel shade',
'To all the regent sisters of the Nine',
'As this poor offering to you, sister mine.',
' ',
'Kind sister! aye, this third name says you are;',
'Enchanted has it been the Lord knows where;',
'And may it taste to you like good old wine,',
'Take you to real happiness and give',
'Sons, daughters and a home like honied hive.',
]
/* Declare a variable that will return the final string */
const result = acrostic.reduce((a, [f]) => a + f, '')
console.log(result)

I am trying to scrape amazon, and stop at a specific number

So this is my code
if (body.included != null && body.included.length > 0) {
let genres = '';
for(let i = 0; i < body.included.length; i++) {
genres += body.included[i].attributes.title;
if(i != body.included.length - 1) {genres += ', ';}
}
embed.addField('GENRES', [`${genres}`,], true);
}
this is the results whenever i search anything with this it gives me this:
Comedy, Kids, Fantasy, Fantasy World, Erotic Torture, Loli, Nudity, Bdsm, Bondage, Sex, Past, Plot Continuity, Violence, Military, Mecha, Historical, Action, Romance, Science Fiction, World War II, Japan, Asia, Piloted Robot, Alternative Past, Steampunk, Gunfights, Alien, War, Robot, Adventure, Space Travel, Cyborg, Crime, Other Planet, Humanoid Alien, Future, Space, Contemporary Fantasy, Vampire, Slice of Life, Detective, Bounty Hunter, Magic, Present, Demon, Super Power, Drama, Anime Influenced, Earth, Love Polygon, Angst, High School, School Life
Has this a example because other types searches comes with 1 or 2 or decent amount of genres where it doesn't have like 40 of them
like this one
Ninja, Fantasy World, Adventure, Action, Comedy, Martial Arts, Super Power, Romance, Disaster, Shounen, Love Polygon, Angst, Plot Continuity, Parallel Universe, Fantasy
So what i need help is how do i make it stop in a certain number where it wont give me 40 of them instead 10 or less
You could change the loop condition but still need to watch out for the length of the body.included array for cases where it has fewer than 10 elements. Try the following:
const MAX_GENRES = 10;
if (body.included && body.included.length) {
const max = Math.min(MAX_GENRES, body.included.length);
const genres = [];
let i = 0;
while (i < max) {
genres.push(body.included[i].attributes.title);
i += 1;
}
embed.addField('GENRES', [genres.join(',')], true);
}
This should achieve what you're after. I don't know the signature for embed.addField() but are you certain that the second argument should be a single-element array containing a string? Could be but seems weird. If the function calls for an array of strings use:
embed.addField('GENRES', genres, true);

Random Testomonial Selection JS

I am working on randomising reviews/testomonials in a website i'm working on.
I am using JS to randomise the testomonials that are on the index page onLoad. In my code, I am using an array to store the testomonials and then when the page loads I want it to just randomly select 3 reviews from the array and write them to "review-1", "review-2" and "review-3" respectively.
The issue I am having with my code is that idk the best way to select 3 different reviews without it repeating the same one twice.
var reviews = [
"Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
"Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
"Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>"
]
var max = reviews.length;
var id1;
var id2;
var id3;
function getRandomReview(max) {
id1 = Math.floor(Math.random() * Math.floor(max));
id2 = Math.floor(Math.random() * Math.Floor(max));
id3 = Math.floor(Math.random() * Math.Floor(max));
}
function randomJS() {
getRandomReview(max);
document.getElementById("review-1").innerHTML = id1;
document.getElementById("review-2").innerHTML = id2;
document.getElementById("review-3").innerHTML = id3;
}
Any advice and help would be appreciated. Thanks in advance
Thanks!
Just shuffled it and it's working! :)
var reviews = [
"Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
"Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
"Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>",
]
var max = reviews.length;
var id1;
var id2;
var id3;
function shuffle(reviews) {
reviews.sort(() => Math.random() - 0.5);
}
function randomJS() {
shuffle(reviews);
document.getElementById("review-1").innerHTML = reviews[0];
document.getElementById("review-2").innerHTML = reviews[1];
document.getElementById("review-3").innerHTML = reviews[2];
}

Compare two string objects for matched string

I was just wondering how I could search and compare two string object and check if either contains a matching string.
I have an associative array containing terms and explanations.
I also have this array broken into two objects "keys"(keys showing the key of the associative array) and "values"(values showing the value of each key in array).
I have another associative array containing a dish and its explanation.
I have split the dish's description into separate words put them into an object.
What I would like to do now is check for every word in descsplit search the TermList and return explanation of term found if found.
eg. free-range is contained in dish explanation, check if there is a match for free-range in TermList and return the value(explanation) of free-range.
Any help would be greatly appreciated, Thanks.
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var values = []; // Creating an object for the values of the terms in TermList
var keys = []; // Creating an object for the keys of the terms in TermList
//function to assign the keys of terms to object keys.
function showkey() {
for (var key in TermList) {
if (TermList.hasOwnProperty(key)) {
keys.push(key);
}
}
//function that shows the value of each key in TermList.
function showValue(){
for( var value in TermList){
values.push(TermList[value]);
}
showkey();
showValue();
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var descsplit = [];
function SplitDesc() {
for (var value in DishList) {
descsplit.push(DishList[value].split(/[\s.,?!:]+/)); // Splits the values of the key up in Dishlist, and puts them into array.Also makes them avoid punctuations while splitting.
}
}
SplitDesc();
//For every word in descsplit search the TermList and return explanation of term found if found
Not tested fully, but this may work
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var keys = Object.keys(TermList);
for(var key in DishList){
var val = DishList[key];
for(var iIndex=0;iIndex<keys.length ;iIndex++){
var term = keys[iIndex];
var regx = new RegExp('\\b'+term+'\\b',"gi");
var found = null;
while((found = regx.exec(val))!=null){
console.log('Found term "'+ term+ '" at index '+found.index);
}
}
}

Break up a string in JS

I have a script built to grab a quote from an array at random, and display it.
I'm trying to format it so it would split the quote and the author like so:
"Insert quote"
Name of person saying Quote
I've tried using split with \n and <br /> and nothing works, even in an alert.
here is my code:
//Initalize the array
var quotes = [];
//Insert data into the array
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto";
quotes[2] = "I'd like to be known as the person who saw things from a different point of view to others." + "Shigeru Miyamoto";
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner";
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker";
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)";
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto.";
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates";
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries";
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis";
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary";
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson";
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary";
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso";
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)";
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel";
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs";
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown";
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban";
//Splits the quote into two pieces, the quote and the person.
var quoteSplit = function (quotes) {
var split = quotes.split("+").replace("\n");
}
//Displays a quote from the array at random.
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote);
//END
When you're building your array, you are concatenating the quote with the author. So this:
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
Ends up with this string being set to quotes[0]
It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban
And your split statement will not work, because the + is not included in the string. This isn't a great way of setting up your array, though. What happens if your quote contains the + symbol, for example?
A better way would be to create an object for each item:
quotes[0] = {
text: "It doesn't matter how many times you have failed, you only have to be right once.",
author: "Mark Cuban"
}
Then you can do:
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote.text + '<br>' + displayQuote.author);
It's seems that + sign is not in your string. The following code:
console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel");
will return to you string
Today’s “best practices” lead to dead ends; the best paths are new and untried.Peter Thiel;
So, you just have to include + sig in your strings like that:
"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel"
As Daniel A. White said in the comments section. You are considering + to be part of the string but you are in fact concatenating 2 strings on each index.
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
should be:
quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs";
Or you could use regex ( Unfortunately I can't provide a regex example right now ) but those are two of your possible options.
If you output any element of your array, you'll see that each entry is a single string with quote and person. Ex.
console.log(quotes[3]);
Stay hungry, stay foolish, stay crazy.Steve Jobs
That's because + concatenates when applied to strings.
As suggested in the comments, you could use split on punctuation marks, although that would break some of your quotes.
You could do something like
quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"];
and output each element separately.
Try this:
var quotes = {
1: {
quote: 'Hello world.',
author: 'Test test'
},
2: {
quote: 'Hello world 2.',
author: 'Test test 2'
},
};
// Display random quote
function displayQuote(){
var key = Math.floor(Math.random() * Object.keys(quotes).length + 1);
return quotes[key].quote + ' ' + quotes[key].author;
};
document.write(displayQuote());

Categories