问题
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