JavaScript > Global Reference

Objects to Strings in JavaScript

How to convert objects to strings in javaScript?


By using String() function we can convert objects to strings.

<p>Click the button to convert objects to strings.</p>
<button onclick="myConvert()">Try it</button>
<p id="demo"></p>

<script>
    function myConvert() {
        var a = 8520;
        var b = "8520";
        var c = new Date();
        var d = Boolean(1);
        var e = Boolean(2);

        var r =
        String(a) + "<br>" +
        String(b) + "<br>" +
        String(c) + "<br>" +
        String(d) + "<br>" +
        String(e);
        document.getElementById("demo").innerHTML = r;
    }
</script>

In the above code snippet we have given ID as "myId" to the second <p> element in the HTML code. There is a function myConvert() in the script code which is connected to the onclick of the HTML button.

We need to convert the objects (Variable values) into strings, for that we are using String() function in variable R

Onclick of the button "Convert" in the HTML code fires the function myConvert() in the script code at the same time String() function convert objects into strings and retunrs  as output.

OUTPUT

 Views: 672 | Post Order: 186



Write for us