user3348643
user3348643

Reputation: 3

String.slice and string.substring

I am brand new at programming, especially JS. I seem to be stuck on a split string.

I need to split a string into two separate strings. I know I can do so with the slice and substr like below, which is my sample I have of what I know. I am assuming my name is Paul Johnson. with below I know that if I have an output of first and last name with the parameters I setup, I will have Paul as my first name and Johnson as my second.

           var str = document.getElementById("fullName").value;

           var firstname = str.slice(0, 4);
           var lastname = str.substr(4, 13); 

My question is that I am getting hung up on how to find the space and splitting it from there in order to have a clean cut and the same for the end. Are there any good resources that clearly define how I can do that?

Thanks!

Upvotes: 0

Views: 308

Answers (6)

user3348643
user3348643

Reputation: 3

I figured it out: var str = document.getElementById("fullName").value; var space = str.indexOf(" ");
var firstname = str.slice(0, space); var lastname = str.substr(space);

Thank you all!

Upvotes: 0

bitoffdev
bitoffdev

Reputation: 3384

Use str.split().

The syntax of split is: string.split(separator,limit)

split() returns a list of strings.

The split() function defaults to splitting by whitespace with to limit.

Example:

var str = "Your Name";
var pieces = str.split();
var firstName = pieces[0];
var lastName = pieces[1];

pieces will be equal to ['Your', 'Name'].

firstName will be equal to 'Your'.

lastName will be equal to 'Name'.

Upvotes: 1

Robert Hickman
Robert Hickman

Reputation: 1147

A good way to parse strings that are space separated is as follows:

pieces = string.split(' ')

Pieces will then contain an array of all the different strings. Check out the following example:

string_to_parse = 'this,is,a,comma,separated,list';
strings = string_to_parse.split(',');
alert(strings[3]); // makes an alert box containing the string "comma"

Upvotes: 1

Patrick Eaton
Patrick Eaton

Reputation: 716

What you're after is String split. It will let you split on spaces. http://www.w3schools.com/jsref/jsref_split.asp

var str = "John Smith";
var res = str.split(" ");

Will return an Array with ['John','Smith']

Upvotes: 3

Egg
Egg

Reputation: 2056

There is a string split() method in Javascript, and you can split on the space in any two-word name like so:

var splitName = str.split(" ");
var firstName = splitName[0];
var lastName = splitName[1];

http://www.w3schools.com/jsref/jsref_split.asp

Upvotes: 1

dsuess
dsuess

Reputation: 5347

str.indexOf(' ') will return the first space

Upvotes: 1

Related Questions