gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:35:20 27 4
gpt4 key购买 nike

我正在尝试编写此函数来检查字符串(第一个参数,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.*/

最佳答案

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

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

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

"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的长度减去它,得到正确的子串进行比较。这将返回从该索引到字符串末尾的所有字符,如 str.length - target.length 中所示,尽管您只需要 target.length 即可使用负指数进行比较。

使用子字符串():

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;
}

或更清洁/替代实现:

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

substr() documentation
substring() documentation

关于Javascript 查找并匹配字符串的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43879253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com