For 循环在字符串中连接变量中的字符(没有 RegExp)- Javascript

For loop inside a string to concatenate the characters in a variable (without RegExp)- Javascript

我正在尝试遍历一个字符串变量并将每个字符保存在另一个变量中。我的代码如下所示:

    var str = "hello world";
    var res = "";

    for (var i = str.indexOf("hello"); i <= str.lastIndexOf("hello"); i++) {
        res = res.concat(str.charAt(i));    
    }

    console.log("The result is: " + res);

这对我来说看起来很合乎逻辑,但它只打印第一个字母。我希望它会打招呼。有什么问题?没有正则表达式就无法完成吗?

str.lastIndexOf("hello")替换为pattern.length:

var str = "hello world";
var pattern = "hello";

var res = "";

var index = str.indexOf(pattern);

for (var i = index; i <= index + pattern.length; i++) {
  res = res.concat(str.charAt(i));
}

console.log("The result is: " + res);

来自文档:

The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.

不是最后一个字符的索引。

您需要长度和起始位置来检查索引。

var str = "bla bla hello world",
    res = "",
    i,
    l = "hello".length,
    p = str.indexOf("hello");

for (i = p; i < p + l; i++) {
    res += str[i];
}

console.log("The result is: " + res);

在字符串中进行 For 循环以连接变量中的字符(没有 RegExp)

var theString = "This is my string";
var theArray = [];
var theResultString = "";

doIt(theString);
doitagain(theString)
function doIt(incomingString)
{
  //concatenate into an array object
  for(var i = 0; i < incomingString.length; i++)
    {
      theArray.push(incomingString.substring(i, i+1))
    }
  console.log(theArray);
}

function doitagain(incomingString)
{
  //concatenating into a string object
  for(var i = 0; i < incomingString.length; i++)
  {
    theResultString += incomingString.substring(i, i+1);
  }
  console.log(theResultString);
}