Joe Torraca
Joe Torraca

Reputation: 2018

JavaScript separate string then decipher number of characters

So what I am doing is taking a string and splitting it at all the spaces. I already did this using .split(" ")[0/1/2] but how do I then take those individual strings and determine the length? The reason I am doing this is to check that string if it has a middle initial or not. Given a name like this John M Smith, I can determine what the words are but if somebody does not enter a middle initial, the last name will now be placed in the middle initial variable. How would I go about doing this or am I tackling it all wrong? Thanks for the help.

Upvotes: 0

Views: 115

Answers (3)

Wayne
Wayne

Reputation: 60414

Use the following:

var parts = "John M Smith".split(" ");
var first = parts[0],
    middle = (parts[2] && parts[1]) || "",
    surname = parts[2] || parts[1];

You'll get the correct values for each variable when there's a middle initial and when there is not. Note that this assumes there is always a first and last name, but that the middle initial is optional.

Upvotes: 0

Digital Plane
Digital Plane

Reputation: 38264

Check the length of the result array to see if there is a middle name:

var result = "John Smith".split(" ");
if(result.length == 2) {
  //No middle name
  //result[0] == "John"
  //result[1] == "Smith"
}
else if(result.length == 3) {
  //Has middle name
}

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

Use the length of the array that holds the separated strings:

var separateStrings = stringVar.split(' ');
var numOfNames = separateStrings.length;

For example, with the following code:

var i = document.getElementById('names'); // assuming an input element of id="names"

i.onkeydown = function(e){
    if (e.keyCode == 13){
        var stringVar = this.value,
            separatedNames = stringVar.split(' '),
            numOfNames = separatedNames.length;

        alert(numOfNames);
    }

};​

JS Fiddle demo.

Upvotes: 1

Related Questions