Break up a string in JS - javascript

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());

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)

Any way of forcing a function with Math.random to return the same value in an expression?

Recently started learning Javascript as a complete newbie to programming. I'm running into an issue while making a Horror film picker that will randomly pick a film from an array, as well as show the picture corresponding to it in a sliding tab.
This is the relevant code for the message(films array is way longer, but can only post two links):
var films = [
["Lake Mungo", "https://upload.wikimedia.org/wikipedia/en/6/68/Lake_Mungo_Official_Poster.jpg"],
["A Tale of Two Sisters", "http://www.thenightmarenetwork.net/wp-content/uploads/2015/10/tale2sisters.png"]
];
function pickFilm() {
return Math.floor(Math.random() * films.length);
}
function showFilm(){
$("#newreplyDiv").append("<img src='" + films[pickFilm()][1] + "'><span id='movieText'><h1>The next film you're watching is: " + films[pickFilm()][0] + " !</h1><h2>" +
"Hope you enjoy it and try to sleep at night alright?</h2></span>")
}
Is there any way of making it return both values for the same index of the array? This version returns a random movie name, then a random picture, not the one in the same sub array, and assigning the value to a function before just locks the value to that index, I need it to be random each time the user clicks the button.
Thank you in advance for any help provided, there probably is a really easy way of fixing it :)
You can make a variable inside the showFilm function to store the random pick, then reuse that:
function showFilm(){
var pickedFilm = pickFilm();
$("#newreplyDiv").append("<img src='" + films[pickedFilm][1] + "'><span id='movieText'><h1>The next film you're watching is: " + films[pickedFilm][0] + " !</h1><h2>" +
"Hope you enjoy it and try to sleep at night alright?</h2></span>")
}

Set HTML elements to random object key:value pairs

I'm trying to use the "database" I have made to cycle through some the quotes at random when the button is clicked and changing the existing quote in the HTML to the random quote and the existing author in the same way
var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
newQuote = myDatabase.[rand].quote;
newAuthor = myDatabase.[rand].author;
});
Firstly your "Database" has syntax errors. It should read:
var myDatabase = [{
"quote": "I have learned silence from the talkative...",
"author": "Khalil Gibran"
}, {
"quote": "One of the blessings of old friends that you can afford to be stupid with them.",
"author": "Ralph Waldo Emmerson"
}, {
"quote": "Once we accept our limits, we go beyond them.",
"author": "Albert Einstein"
}];
Secondly, you're mixing vanilla JS with Jquery. Whilst this isn't technically wrong it's much easier to read if you just stick to one or the other
var newQuote = $('#displayedQuote');
var newAuthor = $('#newAuthor');
Lastly, the syntax in your click method is incorrect. You're assigning a value to the newQuote and newAuthor variables rather than manipulating the element. What you want to do is use the .text() method to add the object values to the DOM.
Also, you don't need the dot notation before the [rand] integer and you want myDatabase.length not database.length
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random() * myDatabase.length)
newQuote.text(myDatabase[rand].quote)
newAuthor.text(myDatabase[rand].author)
});
Here's a working example: https://codepen.io/mark_c/pen/pExxQA
Something like that ?
var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
$(newQuote).text(myDatabase[rand].quote);
$(newAuthor).text(myDatabase[rand].author);
});

Split long string into text chunks with jQuery

I have a long string that needs to be sliced into separated chunks inside an array, with a predefined length limit the chunks. Some rules apply:
If the limit cuts a word, then the word is separated for the next chunk.
Slices must be trimmed (no spaces at the beginning or end of the array item).
Special punctuation .,!? should stay with the word, and not be sent to the next chunk.
Original text: I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.
Result with current code ["I am totally", " unappreciated in my time", ". You can run this whole", " park from this room with", " minimal staff for up to ", "3 days. You think that", " kind of automation is ea", "sy? Or cheap? You know", " anybody who can network ", "8 connection machines", " and debug 2 million line", "s of code for what I bid", " for this job? Because if", " he can I'd like to see h", "im try."]
...it should actually be:
["I am totally", "unappreciated in my time.", "You can run this whole", "park from this room with", "minimal staff for up to 3", "days. You think that kind", "of automation is easy?", "Or cheap? You know anybody", "who can network 8", "connection machines and", "debug 2 million lines of", "code for what I bid for", "this job? Because if he", "can I'd like to see him", "try."]
As you can see, I'm still having trouble with rules 2 and 3.
This is my current code (you can check the working demo in jsfiddle):
function text_split(string, limit, pos, lines) {
//variables
if(!pos) pos = 0;
if(!lines) lines = [];
var length = string.val().length;
var length_current;
//cut string
var split = string.val().substr(pos, limit);
if(/^\S/.test(string.val().substr(pos, limit))) {
//check if it is cutting a word
split = split.replace(/\s+\S*$/, "");
}
//current string length
length_current = split.length;
//current position
pos_current = length_current + pos;
//what to do
if(pos_current < length) {
lines.push(split);
return text_split(string, limit, pos_current, lines);
} else {
console.log(lines);
return lines;
}
}
$(function(){
$('#button').click(function(){
text_split($('#textarea'), 25);
});
});
The html form for the demo:
<textarea id="textarea" rows="10" cols="80">I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.</textarea>
<button id="button">demo</button>
Example for 25 characters max, you can use this pattern:
/\S[\s\S]{0,23}\S(?=\s|$)/g
demo
code example:
var text = " I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.";
var myRe = /\S[\s\S]{0,23}\S(?=\s|$)/g;
var m;
var result = new Array();
while ((m = myRe.exec(text)) !== null) {
result.push(m[0]);
}
console.log(result);
Note: if you need to choose dynamically the max size, you must use the alternative syntax to define your RegExp object:
var n = 25;
var myRe = new RegExp("\\S[\\s\\S]{0," + (n-2) + "}\\S(?=\\s|$)", "g");
pattern details:
\S # a non-space character (it is obviously preceded by a space
# or the start of the string since the previous match
# ends before a space)
[\s\S]{0,23} # between 0 or 23 characters
\S(?=\s|$) # a non-space character followed by a space or the end of the string
Note that (?=\s|$) can be replaced with (?!\S).

In Javascript, how do you access key value data from an object in a mixed array?

my name's Mike and my question is two-fold:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm trying to make a simple flashcard program to help me memorize different kinds of sound equipment. The list of equipment is large but I'm only including three different kinds to keep this example simple. I want each object to have two properties: answer and desc. This first part defines three objects, places them in an array, creates a variable for picking one of the array items randomely, and another variable for prompting the user for an answer:
var newFlash = function() {
var A827 = {
answer: "T",
desc: "Multitrack Tape Recorder"
};
var LA2A = {
answer: "O",
desc: "Classic Leveling Amplifier"
};
var SonyC800G = {
answer: "M",
desc: "Tube Condenser Microphone"
};
var list = [A827, LA2A, SonyC800G];
var rand = Math.floor(Math.random() * list.length);
var question = prompt("What kind of equipment is " + list[rand] + "?");
};
Now, if I make my three items in my array all strings, they show up no problem in the question prompt correctly replacing list[rand] with the appropriate array item. However, using objects in my array, my prompt says "What kind of equipment is [object Object]?.
My end goal is for the user to enter the appropriate one- or two-letter response (M for Microphone, C for Console, O for Outboard Gear, T for Tape Machine, S for Software, and CH for Computer Hardware) where upon entering the successful letter(s) yields an alert that displays both the object's answer and desc. My n00b instinct tells me this second part should be an if/else statement in the form of
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
}
else {
alert("Wrong, try again.");
}
but I'm very certain that this isn't the right way to access these object properties.
So, again, my question has two parts:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm sure some piece of logic is escaping me. Thanks for reading.
You want to use var question = prompt("What kind of equipment is " + list[rand].desc + "?");. list[rand] will yield you an object which has the structure {answer: "", desc: ""}, so you need to additionally access the description in your code.
Similarly, you want:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
}
else {
alert("Wrong, try again.");
}
To access the property of an Object in Javascript you use dot notation, as is common with many languages that have Objects. list is an array of Objects, so when you type list[rand] you are returning one of those Objects. Once you have an Object, you simply need to use the dot notation to access whatever property it is you require, in this case either desc or answer.
So instead of
var question = prompt("What kind of equipment is " + list[rand] + "?");
try
var question = prompt("What kind of equipment is " + list[rand].desc + "?");
Placing the property you are trying to access outside the bracket. This solves your second question as well, simply change:
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
to:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
this fiddle will help demonstrate.

Categories