admin管理员组

文章数量:1394171

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

Thanks

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

Thanks

Share Improve this question asked Jan 20, 2011 at 19:35 AnApprenticeAnApprentice 111k202 gold badges637 silver badges1k bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Example: http://jsfiddle/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(" ")

本文标签: javascriptParsing an Input value using SplitStack Overflow