首页 > 解决方案 > 如何在javascript中找到没有内置函数的子字符串?

问题描述

我正在尝试重建 Substring 函数。这是我的代码。当传递单个参数以及 num1> num2 时它不起作用。谁能告诉我应该在哪里更改?

这是我的代码......

function myFunction(num1, num2) {
  var str = "This is a string";
  var subString = "";
  var len = str.length;

  if (num1 < 0 || num2 > len) {
    console.log("Invalid input");
  } else {
    var k = 0;
    for (i = num1; i < num2; i++) {
      subString = subString + str[i];
      k++;
    }
    console.log(subString);
  }
}
myFunction(0, 4);

标签: javascriptsubstringsubstr

解决方案


You could start with a proper function name and singnature by using the string, start and end index as parameters.

Then start with an empty string and iterate from start to the end or the length of the string.

function substring(string, start, end) {
    var result = '',
        length = Math.min(string.length, end),
        i = start;
  
    while (i < length) result += string[i++];
    return result;
}

console.log(substring('This is a string', 0, 4));
console.log(substring('This is a string', 40, 4));


推荐阅读