I’m trying to replace part of a response before outputting it to a html document. Specifically I want to delete part of the response using replace.
fetch('https://api.foo.bar/5H2F8QXNTRW7P7LNL1KHXL76JQXXI2')
.then(response => response.json())
.then(json.replace(" and null Cent", "")) // trying to delete this part
.then(json => document.getElementById("betrag").innerHTML = json)
.catch(err => console.log('Request Failed', err));
It’s been working fine until I tried to delete part of the response. The console shows
Uncaught ReferenceError: json is not defined
I’m not getting this error without the line trying to replace part of the response. I#m lost.
I tried json.replace and response.replace without success.
2
Answers
The issue here is that you’re trying to use the
replace
method on thejson
object, butjson
is not defined in that scope. Thereplace
method is a string method, so you need to use it on a string.Assuming the API returns a JSON object with a string property that you want to modify, you can do something like this:
If the API returns a plain string, you can simply use the
replace
method on the response text:Note that in the first example, I used
JSON.stringify(json)
to convert the JSON object to a string before assigning it to theinnerHTML
property. This is becauseinnerHTML
expects a string, not a JSON object.