Javascript Separate String Into Different Variables
Solution 1:
.split()
just returns an array, so you can easily assign new variables using that...
var str = "John M Peters";
var fname = str.split(" ")[0];
var mname = str.split(" ")[1];
var lname = str.split(" ")[2];
Solution 2:
You can split the string like so:
var name = 'John M Peters';
var arr = name.split(' ');
var obj = {fname: arr[0]};
if(arr.length === 1) {
obj.lname = arr[1];
} else {
obj.mname = arr[1];
obj.lname = arr[2];
}
console.log(obj.fname);
console.log(obj.mname); //could be undefinedconsole.log(obj.lname);
This solution will also work for a string that does not have a middle initial as well. You can see this example here: http://jsfiddle.net/nDwmY/2/
Solution 3:
If you don't know how many spaces there are in the string, beforehand, you can do the following:
var str = "How are you doing today, my dear friend?";
numberspaces = str.split(" ").length; //you know how many spaces there are
words=str.split(" "); //it creates an array of wordsvar i;
for (i = 0; i < numberspaces; i++){
console.log(words[i]);}
Solution 4:
I would create a function along these lines. This is just a quick-and-dirty and doesn't do any validation, I leave that up to you.
functionparse_name(theName) {
var nameSplit = theName.split(" ");
var nameFields = {
first : nameSplit[0],
middle : nameSplit[1],
last : nameSplit[2]
};
return nameFields;
}
Then you can call it any time you need to parse a name.
var parsedName = parse_name("John M Smith");
alert(parsedName.first); // Should alert "John"
alert(parsedName.middle); // Should alert "M"
alert(parsedName.last); // Should alert "Smith"
Solution 5:
In addition to the answers the others pointed out, I'd like to point out that Mozilla's JavaScript engine (spidermonkey) supports destructuring assignments:
<scriptlanguage="javascript1.7">var s = 'John M. Peters';
var fname, mname, lname;
[fname, mname, lname] = s.split(/\s+/);
alert('fname = ' + fname + ', mname = ' + mname + ', lname = ' + lname);
</script>
This is not portable, so not ideal for web programming. However, if you're writing a plugin for firefox or thunderbird or etc, then there are a number of interesting language extensions available.
Post a Comment for "Javascript Separate String Into Different Variables"