MrCycling
MrCycling

Reputation: 3004

One string multiple variables to check with indexOf

I have written a little JQuery / Javascript add on for our form, that takes a single full name input and breaks it into first and last name components. It opens a modal if there are three or more names in the input and asks which combo is correct.

My next step is finding and stripping any suffix that may have been entered such as Jr, Sr, III, etc. I am currently stripping off the last four characters and checking them with indexOf to see if they contain a suffix string (Jr, Sr, III, etc). But each line checks only one possible suffix and I am wondering is there is some js magic that will check multiple suffixs in one line. My current code is below:

var nameVal = $('#name').val();    
var suffix = nameVal.slice(-4);
if (suffix.toLowerCase().indexOf(" jr") != -1)  { 
    var nameSplit = nameVal.slice(0, -3).split(" "); 
} elseif (suffix.toLowerCase().indexOf(" iii") != -1)  { 
    var nameSplit = nameVal.slice(0, -4).split(" "); 
} else {
    var nameSplit = nameVal.split(" "); }

I can always do the good old || and keep adding extra (suffix.toLowerCase().indexOf(" jr") != -1) with a different indexOf value, but I am hoping to keep the code more compact if possible, my "little" script is already 3k.

Once I get this sorted the last step will be figuring out how to retain the last name value, so that further down the form when other names are entered and the script is called again it can check to see if the selected last name matches the new entry and bypass the modal pop up.

Upvotes: 2

Views: 4080

Answers (3)

Howard Zoopaloopa
Howard Zoopaloopa

Reputation: 3822

In this case I usually make an array of values, (because I'm not good with regex)

var suffixArr = [' jr',' iii', ' ii'];

//then run a loop

for(var i = 0; i < suffixArr.length;i++){
    if(suffixArr[i].toLowerCase().indexOf(suffixArr[i]) != -1){
       nameSplit = nameVal.slice(0, - suffixArr[i].length).split(" "); 
    }
}

Upvotes: 0

Ekin Koc
Ekin Koc

Reputation: 3007

You can use a regular expression. Try something like this;

nameVal = nameVal.replace(/ (jr|sr|I?II)$/gi, "");

In more detail;

(jr|sr|I?II) = jr or sr or II or III
$ = at the end of line
/i = case insensitive
/g match globally

Upvotes: 2

icyrock.com
icyrock.com

Reputation: 28628

Probably best to use regexps for this, for example:

var names = [
  "Joe Jr.",
  "Mark Sr.",
  "Loui III",
  "Mark Lockering",
];

var suffixRes = [
  /Jr\.$/, /Sr\.$/, 'III', 
];
$(names).each(function(i, name) {
   var str = name;
   $(suffixRes).each(function(j, suffixRe) {
       str = str.replace(suffixRe, '');
   });
   console.log(str);
});

Live example:

Upvotes: 0

Related Questions