I am looking to take a string and find all the spaces in it and separate that into different variables. I know I could use the .split() but that wouldn\'t make
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 undefined
console.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/