AMHD
AMHD

Reputation: 387

Output strings to arrays and output items from array

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?!

Upvotes: 2

Views: 53

Answers (3)

Kong
Kong

Reputation: 9546

Match the non-whitespace:

niceday.match(/\S+/g);

Upvotes: 1

bukart
bukart

Reputation: 4906

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

Upvotes: 0

James
James

Reputation: 2201

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';

Upvotes: 0

Related Questions