Skip to content Skip to sidebar Skip to footer

Check If String Ends With The Given Target Strings | Javascript

I am trying to write javascript code that will test if the end of the first string is the same as the target, return true. Else, return false. must use .substr() to obtain the resu

Solution 1:

try:

function end(str, target) {
   return str.substring(str.length-target.length) == target;
}

UPDATE:

In new browsers you can use: string.prototype.endsWith, but polyfill is needed for IE (you can use https://polyfill.io that include the polyfill and don't return any content for modern browsers, it's also usefull for other things related to IE).


Solution 2:

As of ES6 you can use endsWith() with strings. For example:

let mystring = 'testString';
//should output true
console.log(mystring.endsWith('String'));
//should output true
console.log(mystring.endsWith('g'));
//should output false
console.log(mystring.endsWith('test'));

Solution 3:

you can try this...

 function end(str, target) {
  var strLen = str.length;
  var tarLen = target.length;
  var rest = strLen -tarLen;
  strEnd = str.substr(rest);

  if (strEnd == target){
    return true;
     }else{
  return false;
     }  
 return str;
}
end('Bastian', 'n');

Solution 4:

You can try this:

function end(str, target) {
    return str.substring(- (target.length)) == target;
}

Post a Comment for "Check If String Ends With The Given Target Strings | Javascript"