javascript split or slice?

3k Views Asked by At

I have a function that grabs the current user on my page. The variable currentUser equals the full name of the user. Sometimes that is just FirstName LastName but other times it is FirstName MiddleName LastName.

I want to be able to split(or slice) currentUser by " " and set variables FirstName and LastName. And if there is a MiddleName I want it to set the variable MiddleName.

Any help would be appreciated!

EDIT:

What I have tried so far has only returned the first letter of the first name and the last letter of the last name. I haven't tried to set the middle name variable yet. See below. Thank you!

function getCurrentUserEmail() {

var requestUri = "../_api/web/currentUser";
var requestHeaders = {"accept": "application/json;odata=verbose"};
$.ajax({
  url: requestUri,
  contentType: "application/json;odata=verbose",
  headers: requestHeaders,
  success:   function onSuccess(data, request){
                var FullName = data.d.Title;
                var EmailAddress = data.d.Email;
                CurrentUserEmail = EmailAddress;
                CurrentUser = FullName;
                name = CurrentUser.split(" ");
                fName = name[0];
                lName = name[1];                                    
  },
  error: function (error) {}
});
}
6

There are 6 best solutions below

3
On BEST ANSWER

I would think that split is likely to be the best approach:

var segments = currentUser.split(' ');
var firstName = segments[0];
var lastName = segments[segments.length - 1];
var middleName = segments.length === 3 ? segments[1] : undefined;

Here, firstName and lastName work regardless of the length of the array, or how many segments exist, but the middleName will be set when there are exactly 3 segments.

There is likely another way of doing it with splice; it would probably look something like this:

var segments = currentUser.split(' ');

var firstName = segments.splice(0, 1)[0];
var middleName = segments.splice(0, 1)[0];
var lastName = segments.splice(0, 1)[0] || middleName;
if (middleName === lastName) {
    middleName = undefined;
}

alert(firstName + middleName + lastName);

I just don't think that's as clean honestly.

0
On

var

function splitName(input) {
  var arrayName = input.split(' ');
  
  var name = arrayName[0];
  var surname = arrayName[1];

  if (arrayName.length === 3) {
      var middleName = arrayName[1];
      surname = arrayName[2];
  }

  console.log('Name ' + name);
  if (middleName)
      console.log('Middlename ' + middleName);
  console.log('Surname ' + surname);
}

var a = "Name Middlename Surname";
var b = "Name Surname" 

splitName(a);
console.log('#');
splitName(b);

0
On

Use the var s = string.split() function. s[0], s[1], and s[2] values in the array will be the associated in the name portion.

0
On

Create an array by splitting the name on spaces.

  1. pop the array to get the last name.
  2. shift the array to get the first name.
  3. shift the array again to get the middle name. OR (||) that result with a null string in case there's no middle name.

This works only if first name, middle name, and last name contain one word each.

var name= 'Homer J Simpson';
var n = name.split(' ');
lastName= n.pop();             //Simpson
firstName= n.shift();          //Homer
middleName= n.shift() || '';   //J
console.log(firstName+' - '+middleName+' - '+lastName);

var name= 'Homer Simpson';
var n = name.split(' ');
lastName= n.pop();             //Simpson
firstName= n.shift();          //Homer
middleName= n.shift() || '';   //null string
console.log(firstName+' - '+middleName+' - '+lastName);

0
On

You can do this with both split and slice. Here is an example solution using slice:

var firstName = name.slice(0, name.indexOf(" "));
var lastName = name.slice(name.lastIndexOf(" ")+1, name.length);
var middleName = name.slice(name.indexOf(" ")+1, name.lastIndexOf(" "));

Note: there is no way to accurately determine what is a middle name from the string. We assume we are given a string with two or three words, and the middle word is the middle name. Apologies to Mr. Andrew van den Houten and Mr. José Maria De Las Mercedes Acosta.

Demo: JSBin

0
On

So here i made a Vanilla Javascript Solution, being able to clear a lot of problems...

I am using the split function For clearing out the Prefix i am using John Resigs Array Remove Function.

As suggested in the Comment to the Accepted Answer you can get the Middle Array and the irrelevant (prefix) one from your Server, maybe...

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

//You can Add all Irrelevant Words in here
var irrelevant = ["Dr", "baron"];

//here is the case of the NonMiddleNameButStillInTheMiddleStuff
var nonMiddleStuff = ["von"];

//Here is the Code
var full = document.getElementById("fullname").innerHTML;
var names = full.split(" ");
getNameStuffDone(names);

var full = document.getElementById("fullname2").innerHTML;
var names = full.split(" ");
getNameStuffDone(names);

//Function getNameStuffDone
function getNameStuffDone(names) {
  var firstName, lastName, middleName;
  if (names.length > 2) {
    for (var i = 0; i < irrelevant.length; i++) {
      for (var j = 0; j < names.length; j++) {
        if (names[j].toUpperCase() == irrelevant[i].toUpperCase()) {
          names.remove(j, j);
        }
      }
    }
    if (names.length > 2) {
      firstName = names[0];
      if (nonMiddleStuff.indexOf(names[1]) >= 0) {
        lastName = names[1] + " " + names[2];
        names.remove(1, 1);
      } else {
        middleName = names[1];
        lastName = names[2];
      }
    } else {
      firstName = names[0];
      lastName = names[1];
    }
  } else {
    firstName = names[0];
    lastName = names[1];
  }


  if (names.length > 2) {
    alert("With Middle Name: " + firstName + " " + middleName + " " + lastName);
  } else {
    alert("Without Middle Name: " + firstName + " " + lastName);
  }
}
<span id="fullname">Anders von Schnurzenstein</span><br>
<span id="fullname2">Baron Dr Anders Patrick Schnurzenstein</span>