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

时间:2017-05-09 20:27:21

标签: javascript string substr

我正在尝试写这个函数,检查一个字符串(第一个参数,str)是否以给定的目标字符串(第二个参数,目标)结束。我使用过这段代码,但似乎没有用。我该怎么调整呢?



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.*/




10 个答案:

答案 0 :(得分:3)

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

str

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

“如果任一参数小于0或是NaN,则将其视为0。”

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

“如果start为负数,则substr()将其用作字符串末尾的字符索引。”

您可以使用0的长度,并从target的长度中减去它,以获得正确的子字符串进行比较。这会将此索引中的所有字符返回到str中的字符串末尾,尽管您只需要str.length - target.length来使用负索引进行比较。

使用substring():

target.length


使用substr():

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

或更清洁/替代实施:

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

substr() documentation
substring() documentation

答案 1 :(得分:1)

在看到对此案件的持续混淆(缩写为可读性)之后:

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字符串是否以整个 target字符串结尾。

毕竟,这就是.endsWith()方法的作用。它解释了上述测试用例的神秘面纱。

MDN documentation for .endsWith()并没有很好地描述这种方法,但它给出的例子很清楚。

有了这样的理解,你现在可以编写代码了。我不打算给你写,但我会在下面留下一些提示。我为您的测试添加了一些代码,这样他们不仅可以记录结果,还可以返回所需的结果。 (在此处编写的版本中,所有测试都将失败。)



// 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 );




答案 2 :(得分:0)

您可以使用此功能:

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

    return l1 === l2;
}

答案 3 :(得分:0)

您的错误是您正在使用子字符串。请尝试使用str.substr代替substring

答案 4 :(得分:0)

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"));

答案 5 :(得分:0)

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



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"))




答案 6 :(得分:0)



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))




答案 7 :(得分:0)

这个怎么样?

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

答案 8 :(得分:0)

您可以使用chatAt()

var (
  client *elastic.Client
)

func a() {
  client.Search()
}

func main() {
  c, err := elastic.NewClient()
  client = c
}

答案 9 :(得分:0)

最简单的方法:

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

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