You need to enable JavaScript to run this app. JavaScript使用replaceAll替换响应字符串未生效是什么原因?
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript使用replaceAll替换响应字符串未生效是什么原因?

问题核心

JavaScript 字符串是不可变类型,所有字符串操作方法(包括replaceAll)都不会修改原字符串,只会返回处理后的新字符串。你当前的代码没有接收replaceAll的返回值,替换后的结果直接被丢弃了,因此原变量s没有变化。


修复方案1:修正字符串替换写法

把replaceAll的返回值重新赋值给s即可:

const xhttp = new XMLHttpRequest();

xhttp.onload = function() {
    let s = xhttp.responseText;
    // 接收返回值覆盖原变量
    s = s.replaceAll("state","item");
    s = s.replaceAll("number","count");

    const jsonArray = JSON.parse(s);
    console.log(s);
}

xhttp.open("GET","http://localhost:8080/plot");
xhttp.send();

修复方案2:更稳妥的JSON属性修改(推荐)

直接修改响应字符串有风险:如果响应的字段值里刚好包含state/number字符串,也会被误替换。更稳妥的方式是先解析JSON,再遍历修改属性名:

const xhttp = new XMLHttpRequest();

xhttp.onload = function() {
    const jsonArray = JSON.parse(xhttp.responseText);
    // 遍历数组修改属性名
    const modifiedArray = jsonArray.map(item => {
        return {
            count: item.number,
            item: item.state
        }
    })
    console.log(modifiedArray);
}

xhttp.open("GET","http://localhost:8080/plot");
xhttp.send();

内容的提问来源于stack exchange,提问作者AmineBinOthman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:51:02