1

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 new variables. I would prefer to not use jQuery or other JavaScript library but if I have to, it wouldn't be the worst thing. Thanks!


Example, John M Peters would result in the variables fname: John, mname: M and lname: Peters.

2
  • Do all names always have a middle initial? Commented Feb 23, 2012 at 3:45
  • No they don't. I am doing a check before I split it to see if there is a middle initial. Commented Feb 23, 2012 at 3:46

5 Answers 5

6

.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];
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I so look forward to the future, when we will be able to do let [fname, mname, lname] = str.split(" ");
I think you can do something like this in coffee-script at least: [fname, mname, lname] = "John M Peters".split(' ')
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 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/

Comments

1

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 words
var i;
for (i = 0; i < numberspaces; i++){
console.log(words[i]);}

Comments

0

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.

function parse_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"

Comments

0

In addition to the answers the others pointed out, I'd like to point out that Mozilla's JavaScript engine (spidermonkey) supports destructuring assignments:

<script language="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.

1 Comment

Correct, hence my caveat about portability ;p. But the OP did not specify the purpose of this JS code. For a plugin or such it's completely appropriate.

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.