1

I need to compare some strings in Javascript, and check if a string is at the end or in the middle.

Example : If by searching for people named "Depp" I get

["Bob Deppo", "Johnny Depp"]

then the ordered output should be

["Johnny Depp", "Bob Deppo"]

Basically I am looking for am way to verify the existence of a substring at the end of another string. Something like :

people.sort(function(a,b){

 if(a.indexOf(" Depp"+[ AND NOTHING MORE ])!== -1) return 1;

});

A few example would be :

"Johnny Depp".indexOf(" Depp"+[ AND NOTHING MORE ] !== -1 ) = TRUE
"Bob Deppsomething".indexOf(" Depp"+[ AND NOTHING MORE ] !== -1 ) = FALSE

If this [AND NOTHING MORE] symbol which would signal the end of a string exists, does one for the beginning of a string also exist ?

Possible Solution (but very nasty) :

One way of doing it would be to get the index of that substring " Depp" with indexOf (6) and see if added together with the length of the substring "Depp" (5) we get the total length of the string "Johnny Depp" (11)

function atEnd(substring, string){
    return (string.indexOf(substring) + substring.length == string.length);
}

Not very elegant though.

So does such a [AND NOTHING MORE] symbol exist ?

Thanks !

Daniel Danny
  • 139
  • 9

0 Answers0