使用Substring()和Substr()来处理两个字符串

时间:2016-09-29 14:03:42

标签: javascript

假设我们必须使用Substring()和/或Substr()或两个字符串方法对字符串var first = "hi my name is this";var second = "this";进行检查,以查看第二个字符串是否与第一个字符串的结尾匹配(我知道String.prototype.endsWith())。怎么办?感谢

到目前为止,我有这个,但错了

function confirmEnding(str, target) {
  // calculate the length of second string
  // remove the end of the first string (same amount) with the first string
  //compare the two
  var secondStringLen = target.length;
  var firstStringLen = str.length;
  var firstStringEnding = str.substring(secondStringLen+1, -1);

  return firstStringEnding;
}

confirmEnding("abcaqwexefg", "efg");

1 个答案:

答案 0 :(得分:-1)

你可以这样试试!



var first = "hi my name is this";
var second = "this";

function confirmEnding(str1, str2) {
  var l1 = str1.length,
    l2 = str2.length;

  var str = str1.substring(l1 - l2);

  if (str == str2)
    return true;
  else
    return false;
}

console.log(confirmEnding("abcaqwexefg", "efg"));
console.log(confirmEnding(first, second));