代码之家  ›  专栏  ›  技术社区  ›  Marvin

为什么.子字符串(索引)不起作用?

  •  0
  • Marvin  · 技术社区  · 7 年前

    How do I replace a character at a particular index in JavaScript?

    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错误(我在本地主机服务器上编程)。 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"],
        [""],
        [""],
        [],
        [],
    ];
    

            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 ,页面停止加载,弹出窗口显示页面无响应。为什么会这样?我该怎么修? Unresponsive page

    4 回复  |  直到 7 年前
        1
  •  1
  •   Robin Zigmond    7 年前

    由于您的错误版本 replaceAt # # 再向前移动几个字符,循环就变得无限大并阻塞浏览器。

    我相信你是想用这个来代替:

    String.prototype.replaceAt = function(index, replacement) {
        return this.substring(0, index) + replacement + this.substring(index + 1);
    }
    

    + 1 -这是唯一的改变!)

        2
  •  1
  •   CertainPerformance    7 年前

    # 向上移动字符串,导致无限循环:

    String.prototype.replaceAt = function(index, replacement) {
        return this.substring(0, index) + replacement + this.substring(index);
    }
    console.log('foo#bar'.replaceAt(3, 'baz'));

    replace .replace ? 使用全局正则表达式匹配 # s、 并替换为 '%23'

    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"],
        [""],
        [""],
        [],
        [],
    ];
    const fixedFileNames = fileNames.map((arr) => (
      arr.map((str) => str.replace(/#/g, '%23'))
    ));
    console.log(fixedFileNames);

    for 循环-没有手动迭代,更好的抽象。

        3
  •  0
  •   Andrew Ridgway    7 年前

    两件事,然后解决。

    1. 通常不赞成将内容附加到内置对象类型上。我建议使用独立函数。

    String.prototype.replaceAt = function(index, replacement) {
        return this.substring(0, index) + replacement + this.substring(index + numberOfCharsToOmit);
    }
    

    适当地加上一个数字。

        4
  •  0
  •   David Kiff    7 年前

    嗯,我不太喜欢这样改变弦的原型。

    如果您的目的是对哈希字符进行编码,为什么不使用:

    编码器组件(“#”)