2

I'm sure this is really simple but I am learning Javascript and I can't figure this out.

 var niceDay = "please, have a nice day";
  1. How do I create an array using "niceDay", and output the array?
  2. how do I output the item in index 2?!

3 Answers 3

1

Match the non-whitespace:

niceday.match(/\S+/g);
Sign up to request clarification or add additional context in comments.

2 Comments

And to output element 2: niceDay.match(/\S+/g)[2]
Thank you Kong! I love the coding your showing me but I don't understand it. Is that Javascript? I'm soooo new to this. lol. I def need to learn this!!! :)
0

You can use the 'split' javascript function. This will split a string on a certain character and return an array:

var array = niceDay.split(' ');

This will return an array split on each space in the string. You can then access the second item in the array using:

var item = array[1];

Or assign the second item a new value using:

array[1] = 'string';

2 Comments

Thank you for your help Judder! Silly question about my 2nd question thou…I want to make sure I'm on the same page. Once I use split() for my array, to get index[2] in niceDay, would I say niceDay[2];? Would the word 'have' then display?
A javascript array index is zero based meaning it starts at zero so in order to get the second item ('have') you would need to use array[1] in the array you returned from the split method. Array[2] would return the third item ('a')
0

Well this should be simple, that's true

Here's a solution

var niceDay = "please, have a nice day";
var niceDarray = niceDay.split(' '); // splits the string on spaces

// alerts each item of the array
for (var i = 0; i < niceDarray.length; i++) {
    alert(niceDarray[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.