Confirm the Ending of an String (Varying Ending Length)

This task requires that you write a function that takes two arguments. The first argument is a string called str and the second argument is a string that our target ending named target . The task is to verify that the ending of str is identical to the target ending. The instructions indicate to use the .substr() method to compare the endings to the targets. The problem I have is that there are going to be multiple starting points and length arguments for the .substr method since the target endings can be of variable length. Take a look at my attempt to solve this issue and please direct me in the right path.

function end(str, target) {
  var start = str.length - (target.length - 1);
  if(str.substr(start, str.length) == target){
     return true;
  } else {
     return false;
  }
}

end('Bastian', 'n');

EDIT

As @torazaburo said. The correct answer Is:

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

Because The string does end with a null string

ORIGINAL ANSWER

function end(str, target) {
    return target.length > 0 && target === str.substr(str.length - target.length);
}

http://jsfiddle.net/tqsx0gLa/2/

From Comments: This code is setting up a logical comparison using the && operator. The left side target.length > 0 should always return true with a valid target input. The left side is setting target equal to the substr starting at the point located by taking the str.length (the position at the far right of the str ) and subtracting the target length (to arrive at the start point of our substring). There is no need for an end point input because the substring will run to the end of str .


这是一个简单的解决方案:

function confirmEnding(str, target) {

  var result;

  //getting the last string depend on target length 
  var last = str.substring(str.length - target.length);   

  //checking the last string with the target
  if(last === target){ 

     result = true;

  } else {

   result = false;
  }

return result;
}

function end(str, target) {
  var start = str.length - target.length;

  if(str.substr(start) == target){
    return true;
  }
  else {
    return false;
  }
}

你也可以试试这个代码。

链接地址: http://www.djcxy.com/p/83902.html

上一篇: JavaScript endsWith功能不起作用

下一篇: 确认字符串的结束(变化结束长度)