我在我的javascript中有一個Json對象 我想用'hello'替換所有'hi'的實例。 這是我的代碼我想用替換函數掃描一個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;
}
使用此功能後,只有打印{ 「你好」:[{ 「男人」: 「你好」, 「你好」: 「你好」}]} ..任何通過創建「陽光
當您運行代碼時出現錯誤。 'str'不是一個字符串,它是一個數組。數組沒有'.replace()'方法。 –
你需要在替換之前將str轉換爲String。轉換你的對象,你可以使用[json stringify](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/JSON/stringify) –
@RayLloy你能告訴我更多,因爲我很新增JS和JSON。 –