我正在尝试编写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');
答案 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'));