Parsing an Input value using Split
<input type="text" id="personName" />
Given possible values like:
- James
- James Bond
- James Van Bond
- James Van Bond the Very First
I want to learn how to split the value by space, and then obtain the first value as FirstName and all the remaining values as Last name.
Possible? Is split the way to do this?
开发者_Go百科Thanks
Example: http://jsfiddle.net/EpbVc/
var value = $('#personName').val().split(' ');
var firstName = value.shift();
var restOfNames = value.join(' ');
Uses .split()
to split on a single space. If there could be multiple spaces, you could use .split(/\s+/)
.
Then it uses .shift()
to remove the first item from the Array, and assign it to firstName
.
Finally it uses .join()
to join the rest of the Array into a string using a single space as the separator.
use .split(" ") to split into array and then use .join(" ")
精彩评论