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


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