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

时间:2022-09-13 13:26:01

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.

我正在尝试编写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 个解决方案

#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).

在新的浏览器中,您可以使用:string.prototype.endsWith,但IE需要使用polyfill(您可以使用包含polyfill的https://polyfill.io,不要为现代浏览器返回任何内容,它对其他浏览器也很有用)与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:

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

#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).

在新的浏览器中,您可以使用:string.prototype.endsWith,但IE需要使用polyfill(您可以使用包含polyfill的https://polyfill.io,不要为现代浏览器返回任何内容,它对其他浏览器也很有用)与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:

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