How to Split a String in JavaScript

If we have a person's name in a string, e.g. Jon Smith, we can find the first and last names using the split function:

var name = 'Jon Smith';
var parts = name.split(' ');
alert('Your first name is: ' + parts[0]);
alert('Your last name is: ' + parts[1]);

The result is:

followed by:

We passed a space character, i.e. ' ', to the split function, and it broke up the string wherever it found the character. The value returned was an array.

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.