How to convert a string object representation to a string in javascript ?

Active February 15, 2022    /    Viewed 161    /    Comments 0    /    Edit


Examples of how to convert a string object representation to a string in javascript:

Create a string object

To create a string object a solution is to use String

let mystringobj  = new String('Hello World !');

then if we test that mystringobj is a string

console.log(typeof mystringobj === 'string');

it returns

false

However if we test if it is a instanceof String

console.log(mystringobj instanceof String);

it returns

true

Convert string object to string

To convert a string object to string a solution is to use stringify:

let mystring = JSON.stringify(mystringobj);

Then

console.log(typeof mystring === 'string');

gives

true

while

console.log(mystring instanceof String);

gives now

false

Example with another object

var myobj = {
    firstname: 'John',
    lastname: 'Doe',
};

var firstname = myobj.firstname;

console.log(typeof firstname === 'string');

returns

true

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount