Check if string ends with the given target strings | javascript

懵懂的女人 提交于 2019-12-19 04:55:24

问题


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 result.

function end(str, target) {
myArray = str.split();
//Test if end of string and the variables are the same
if (myArray.subsrt(-1) == target) {
 return true;
}
else {
 return false;
}
}

end('Bastian', 'n');

回答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).




回答2:


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');



回答3:


You can try this:

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



回答4:


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'));


来源:https://stackoverflow.com/questions/30153942/check-if-string-ends-with-the-given-target-strings-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!