【发布时间】:2018-10-30 22:06:06
【问题描述】:
下面是来自How do I replace a character at a particular index in JavaScript?的自定义String方法
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}
我不希望替换来替换进行中的字符,所以我将其更改为
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index);
}
我用它来用 '%23' 替换 '#' 因为否则浏览器不理解链接会给出 404 错误(我在 localhost 服务器上对此进行编程)。
我的fileNames 数组看起来像
const fileNames = [
["template.html", "first.php", "second.php", "comments.php", "predefined.php", "strings.php", "concat.php",
"numbers.php", "constants.php", "quotes.php"],
["form.html", "handle_form #1.php", "handle_form #2.php", "handle_form #3.php"],
[""],
[""],
[],
[],
];
然后我循环遍历二维数组。最后,我用另一个循环遍历 fileNames 中的每个字符串。如果以下代码被注释掉,它工作正常,但代码完成的任务没有执行。
for (let k = 0; k < fileNames[i][j].length; k++) {
if (fileNames[i][j][k] == '#') {
fileNames[i][j] = fileNames[i][j].replaceAt(k, '%23');
}
}
}
}
问题是,当我将 index + replacement.length 更改为 index 时,页面停止加载,并出现一个弹出窗口,提示页面无响应。为什么会这样?我如何解决它?
【问题讨论】:
-
你能用你找到的原始解决方案澄清问题吗?
-
“问题是,当我将 index + replacement.length 更改为 index 时,页面停止加载,并出现一个弹出窗口,提示页面无响应。”
-
抱歉不清楚。我指的是改变它的原因。
-
哦,改变它的原因是这些是链接。在 URL 中,它不会自动将“#”编码为“%23”,所以我必须自己做。无论哪种方式,它都会返回一个 404。例如,在 handle_form #1.php 中它必须更改为 handle_form%20%231.php 否则它会更改为 handle_form%20%23php.我不希望它替换 '1' 和 '.'
-
我明白了,这是有道理的。对不起。
标签: javascript substring