我想使用replace函数扫描json对象,然后用字符串替换匹配的单词

I want to to use the replace function to scan a json object and then replace the matched word with a string

本文关键字:替换 字符串 然后 单词 对象 replace 函数 json 扫描      更新时间:2023-09-26

我的javascript中有一个Json对象我想用"你好"替换"嗨"的所有实例。这是我的代码

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var res1 = /hi/gi;
    var str = [{"hi":"new","hi":"sun","hi":"hi"}]; 
    var res = str.replace(res1, "hello");
    document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>   

如有任何帮助,我们将不胜感激。感谢

编辑:

function myFunction() {
    var res1 = /hi/gi;
    var str = {"hi":[{"men":"hi","hi":"sun","hi":"hi"}]}; 
    var mouse = JSON.stringify(str);
    var res = mouse.replace(res1, "hello");
    document.getElementById("demo").innerHTML = res;
}

使用此功能后,它只打印{"hello":[{"men":"hello,"hello":"hello"}]}。。为什么不打印"你好":"sun?

这不是JSON对象,这只是一个Javascript对象。JSON确实有smae语法,但不要将它们混合在一起。

此外,通过创建这样的对象,这里就是您创建的:

  1. []->str是一个数组

  2. 〔{}〕->str是一个数组,他的第一个值是对象

  3. 对象的键值

最后:str[0].hi将具有值"hi"或"new"(不知道会忽略哪一个)。str[0].sun将具有值"hi"。

我不明白你为什么要重命名对象的键。如果要替换所有值:

for(key in str[0]){
   str[key] = str[key].replace(res1, "hello");
}