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!
-
So you're asking how to split a string on a space character?cookie monster– cookie monster2014年02月24日 21:59:53 +00:00Commented Feb 24, 2014 at 21:59
-
maybe devdocs.io is a nice place to search functions and theri meanings devdocs.io/javascriptdsuess– dsuess2014年02月24日 22:01:55 +00:00Commented Feb 24, 2014 at 22:01
6 Answers 6
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']
1 Comment
str.indexOf(' ') will return the first space
1 Comment
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];
1 Comment
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"
Comments
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'.
1 Comment
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!