Javascript 查找并匹配字符串的最后一项

Javascript find and match last item of the string

我正在尝试编写此函数来检查字符串(第一个参数,str)是否以给定的目标字符串(第二个参数,target)结尾。我已经使用了这段代码,但它似乎不起作用。我该如何调整它?

function confirmEnding(str, target) {
  var last = str.substring(-1);
  var last2 = target.substring(-1);
  if (last == last2) return true;
  else if (last !== last2) return false;
}

confirmEnding("Walking on water and developing software from a specification 
    are easy if both are frozen", "specification") )/*should return "false".
    confirmEnding("Bastian", "n") should return true.
    confirmEnding("Connor", "n") should return false.
    confirmEnding("Walking on water and developing software from a specification 
    are easy if both are frozen", "specification") should return false.
    confirmEnding("He has to give me a new name", "name") should return true.
    confirmEnding("Open sesame", "same") should return true.
    confirmEnding("Open sesame", "pen") should return false.
    confirmEnding("If you want to save our world, you must hurry. We dont know 
    how much longer we can withstand the nothing", "mountain") should return 
    false.
    Do not use the built-in method .endsWith() to solve the challenge.*/

你可以使用这个功能:

function confirmEnding(a, b) {
    var l1 = a[a.length - 1];
    var l2 = b[b.length - 1];

    return l1 === l2;
}

您的错误是您使用了子字符串。尝试 str.substr 而不是 substring

function confirmEnding (str, target) {
   return  str.substr(-1) == target.substr(-1);  
 }

console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"));

为什么要检查最后的话是否相同:

const confirmEnding = (str, target) => new RegExp(`${target}$`, '').test(str)

console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"))

console.log(confirmEnding("Bastian", "n"))
console.log(confirmEnding("Connor", "n"))
console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"))
console.log(confirmEnding("He has to give me a new name", "name"))
console.log(confirmEnding("Open sesame", "same"))
console.log(confirmEnding("Open sesame", "pen"))
console.log(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain"))

const a = "Walking on water and developing software from a specification are easy if both are frozen", 
 b = "specification";
  
// your function
const equalLastLetter = (a, b) => a.substr(-1) === b.substr(-1);

console.log(equalLastLetter(a, b))

这个怎么样?

function confirmEnding (str, target) {
    var last  = str.charAt(str.length-1);
    var last2 = target.charAt(target.length-1);
    return (last == last2);
}

为了通过所有具有所需 return 值的测试,该函数不应该比较字符串的最后一个字符,而是比较整个字符串,target 到相应的str 的结束子串。您需要 target 的长度才能找到 str 中相应子串的正确起始索引,如下所示:

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

您的代码正在比较整个字符串。请参阅下面的 substring() 文档。 -1 默认为 0 因此 return 从索引 0 开始的子字符串和 return 字符串的其余部分(整个字符串)因为没有结尾给出了索引。 .

"If either argument is less than 0 or is NaN, it is treated as if it were 0."

如果要使用负索引,可以使用 substr() 方法而不是 substring()substr() 识别负索引值而不是默认为 0.

"If start is negative, substr() uses it as a character index from the end of the string."

可以用target的长度减去str的长度得到正确的子串进行比较。这将 return 从该索引到字符串末尾的所有字符,如 str.length - target.length 中一样,尽管您只需要 target.length 来使用负索引进行比较。

使用 substring():

function confirmEnding (str, target) {
   var last  = str.substring(str.length-(target.length));
   if (last == target ) return true;
   else return false;
 }


使用 substr():

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

或 cleaner/alternate 实现:

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

substr() documentation
substring() documentation

您可以使用chatAt()

function confirmEnding (str, target) {
   var last  = str.charAt(str.length -1);
   var last2 = target.charAt(target.length -1);
   return last === last2 ;
}

最简单的方法:

const confirmEnding = (_str, _target) => _str.charAt(_str.length - 1) === _target.charAt(_target.length - 1);

https://jsfiddle.net/pablodarde/hsdgjmzw/

在看到关于这个案例的持续混乱之后(为了便于阅读而缩写):

confirmEnding(
    "Walking on water...both are frozen",
    "specification"
);  // Should return false (why not true?)

还有这个有趣的注释:

/* Do not use the built-in method .endsWith() to solve the challenge. */

我有预感可能发生了什么。

仔细检查此问题的说明。您确定要测试每个字符串的最后一个 字符 是否相同吗?听起来您应该测试 src 字符串是否以 entire target 字符串结尾。

毕竟,这就是 .endsWith() 方法的作用。并且解释了上面测试用例的奥秘。

MDN documentation for .endsWith()对方法描述的不是很好,但是给出的例子很清楚

有了这个理解,您现在可能可以编写代码了。我不会为你写它,但我会在下面给出一些提示。我为您的测试添加了一些代码,以便它们不仅记录结果,而且记录它们是否 return 所需的结果。 (在此处编写的版本中,所有测试都会失败。)

// Return true if str ends with target, false if it does not
function confirmEnding( str, target ) {
    // You can do this in a single return statement
    // with one === comparison in it. The .slice()
    // method will help you here, and you only need
    // to pass a single argument into it.
    // You don't need any if statements, intermediate
    // variables, or anything fancy.
    // There are several other ways to do it too, including
    // the approach shown on the MDN page.
}

function testEnding( str, target, desired ) {
    var result = confirmEnding( str, target );
    console.log(
        '"' + str + '"',
        '"' + target + '"',
        'returns', result,
        result === desired ? 'Good' : 'WRONG!'
    );
}

testEnding( "Bastian", "n", true );
testEnding( "Connor", "n", false );
testEnding( "Walking on water and developing software from a specification are easy if both are frozen", "specification", false );
testEnding( "He has to give me a new name", "name", true );
testEnding( "Open sesame", "same", true );
testEnding( "Open sesame", "pen", false );
testEnding( "If you want to save our world, you must hurry ); We dont know how much longer we can withstand the nothing", "mountain", false );