Understand the following exercise of js loops and strings in array - javascript

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)

Related

Dynamically Find Values from a Variable

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`);
}

How to remove colon based emojis from text using javascript

How can i remove all instances of :smile: style emjois from a string using javascript? Here is an example below I got in JSON with :point_right: in it. I'd love to remove all of them from a string.
[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }
Just use String.prototype.replace() with a regular expression:
const input = 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”';
const output = input.replace(/:\w+:/g, '');
console.log(output);
Assuming the emojis are all one word, between :s:
const obj = {
service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299'
}
obj.title = obj.title.replace(/:[^ ]+:/g, '');
obj.text = obj.text.replace(/:[^ ]+:/g, '');
console.log(obj);
From this answer Replacing values in JSON object you could do this :
var json=[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }];
var rep = JSON.stringify(json).replace(/(“)(:[^:]+:)/g, '$1');
var New = JSON.parse(rep);
console.log(New);
Try this :
// JSON Object
var jsonObj = [{
"service_name": "Instagram",
"title": "Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”",
"text": "36 Likes, 2 Comments - “:point_right: Real people, making real products",
"ts": "1523497358.000299"
}];
// Replace :point_right: with blank string.
jsonObj.map(obj => {
obj.title = obj.title.replace(":point_right: ", "");
obj.text = obj.text.replace(":point_right: ", "");
return obj;
});
// Output
console.log(jsonObj);

Is there a way (using Lodash or Underscore) to see if a string in an array of strings contains a substring from another array?

I have an array of strings:
["General election 2017: No cut to UK aid spending, says May", "Paris Champs Elysees attack gunman named as Karim Cheurfi", "William and Kate surprise Radio 1 visit", "South Africa bus crash 'kills at least 19 children'", "Len McCluskey re-elected as Unite general secretary", "Cleethorpes car crash captured on CCTV", "Adam Johnson prison video investigated", "Julian Assange's arrest a 'priority' for US attorney general", "Shrewsbury trust warned over baby heart monitoring in 2007", "High heels row: Petition for work dress code law rejected"]
I want to see if any string in the above array has a substring from another array:
["South Africa", "United States"]
If it does, do xyz.
I've tried using _.difference (lodash) and _.intersection (underscore), but I don't think it compares the strings for substrings.
P.S. Sorry for the crazy array strings - they are news articles from a returned JSON.
Thanks for your help...
if(_.intersection(arr, check).length > 0){
//do something
}else {
//do something
}
you can use indexOf method from javascript
var arr = ["General election 2017: No cut to UK aid spending, says May", "Paris Champs Elysees attack gunman named as Karim Cheurfi", "William and Kate surprise Radio 1 visit", "South Africa bus crash 'kills at least 19 children'", "Len McCluskey re-elected as Unite general secretary", "Cleethorpes car crash captured on CCTV", "Adam Johnson prison video investigated", "Julian Assange's arrest a 'priority' for US attorney general", "Shrewsbury trust warned over baby heart monitoring in 2007", "High heels row: Petition for work dress code law rejected"];
var check = ["southa frice", "usa"];
var found = false;
for (var i = 0; i < check.length; i++) {
if (arr.indexOf(check[i]) > -1) {
found = true;
break;
}
}
console.log(found);
Here is a one-liner to do this (with ES6 arrow functions, so you might need to rewrite it to regular function(){} if you are not transpiling). You dont need lodash at all.
var a = ["General election 2017: No cut to UK aid spending, says May", "Paris Champs Elysees attack gunman named as Karim Cheurfi", "William and Kate surprise Radio 1 visit", "South Africa bus crash 'kills at least 19 children'", "Len McCluskey re-elected as Unite general secretary", "Cleethorpes car crash captured on CCTV", "Adam Johnson prison video investigated", "Julian Assange's arrest a 'priority' for US attorney general", "Shrewsbury trust warned over baby heart monitoring in 2007", "High heels row: Petition for work dress code law rejected"];
var b = ["South Africa", "United States"];
var match = a.filter(source => b.some(substring => source.includes(substring)));
Or with lodash (_.includes and _.filter):
var a = ["General election 2017: No cut to UK aid spending, says May", "Paris Champs Elysees attack gunman named as Karim Cheurfi", "William and Kate surprise Radio 1 visit", "South Africa bus crash 'kills at least 19 children'", "Len McCluskey re-elected as Unite general secretary", "Cleethorpes car crash captured on CCTV", "Adam Johnson prison video investigated", "Julian Assange's arrest a 'priority' for US attorney general", "Shrewsbury trust warned over baby heart monitoring in 2007", "High heels row: Petition for work dress code law rejected"];
var b = ["South Africa", "United States"];
var match = _.filter(a, source => b.some(substring => _.includes(source, substring)));
Using lodash#intersectionWith:
This method is like _.intersection except that it accepts comparator
which is invoked to compare elements of arrays. The order and
references of result values are determined by the first array. The
comparator is invoked with two arguments: (arrVal, othVal).
_.intersectionWith(news, words, (article, word) => article.includes(word));
Using ES6:
news.filter(article => words.some(word => article.includes(word)));
Using usual Javascript:
news.filter(function(article){
return words.some(function(word){
return article.indexOf(word) > -1;
});
});
Array.indexOf()
It will helps you. Iterate through news array and find the country name index is present by iterating country array.

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