我试图循环遍历一个字符串变量并将每个字符保存在另一个变量中。我的代码如下所示:
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);
这对我来说看起来很合乎逻辑,但它只打印第一个字母。我以为它会打招呼。有什么问题?没有正则表达式就无法完成吗?
最佳答案
您需要长度和起始位置来检查索引。
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);
关于javascript - For 字符串内循环以连接变量中的字符(不使用 RegExp)- Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947786/