检查字符串是否以给定的目标字符串结束JavaScript的

时间:2015-05-10 16:42:51

标签: javascript arrays substr

我正在尝试编写javascript代码,测试第一个字符串的结尾是否与目标相同,返回true。否则,返回false。必须使用.substr()来获得结果。

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

4 个答案:

答案 0 :(得分:7)

尝试:

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

<强>更新

在新版浏览器中,您可以使用:string.prototype.endsWith,但IE需要使用填充(您可以使用包含polyfill的https://polyfill.io并且不会为现代浏览器返回任何内容,而且#&# 39; s对于与IE相关的其他事情也很有用。

答案 1 :(得分:0)

你可以试试这个......

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

答案 2 :(得分:0)

您可以尝试以下方法:

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

答案 3 :(得分:0)

从ES6开始,您可以对字符串使用endsWith()。例如:

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