Francesco
Francesco

Reputation: 3

How to modify text in Javascript

I made a script to retrieve data from an API and show it in HTML. The problem is that the API answers with something like that

[{"seen":"2021-08-24 04:13:51"}]

And I want the user to see something like

2021-08-24 04:13:51

How can i modify this text inside of javascript? (The output is variable but the number of characters is always the same, idk if this is a useful info...)

Upvotes: 0

Views: 133

Answers (3)

Fabrizio Beccaceci
Fabrizio Beccaceci

Reputation: 430

The server is returning data in json format, you need to parse the response to a javascript object and then you can use the value as you want

const theServerResponse = '[{"seen":"2021-08-24 04:13:51"}]'

const parsedResponse = JSON.parse(theServerResponse)


//At this point you can get that value
parsedResponse[0].seen

Upvotes: 1

Nitheesh
Nitheesh

Reputation: 19986

What you have to do is set innerText value from the JSON. You can access the value using response[0].seen

const response = [{"seen":"2021-08-24 04:13:51"}];
console.log(response[0].seen);
document.getElementById('lastupdatedon').innerText = response[0].seen;
<p id="lastupdatedon"></p>

Upvotes: 2

Prakash
Prakash

Reputation: 372

Use below script

                var fromAPI='[{"seen":"2021-08-24 04:13:51"}]';
                var data=JSON.parse(fromAPI);
                if(data!=null && data.length>0)
                {
                    document.getElementById('lastupdatedon').innerText = data[0].seen;
                }

HTML

<h3 id="lastupdatedon"></h3>

Do not forget to check for nulls, index is greater than 0. IF server doesnt return data then your app will throw an error of undefined.

Upvotes: 1

Related Questions