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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@AnApprentice. The .split() will still work with a single word. You're getting undefined back as the value, so there may be a problem with your selection. Is the DOM ready?
You could first get the .val(), then test to see if you received any input before continuing. var value = $('#personName').val(); if( value ) { /*do the rest*/ }
0

use .split(" ") to split into array and then use .join(" ")

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.