JavaScript String.valueOf() Method
-
Syntax of JavaScript
string.valueOf()
: -
Example Codes: Use the
string.valueOf()
Method to Convert a String Object Into a String -
Example Codes: Use the
string.valueOf()
Method to Display String Object as HTML Text
The string.valueOf()
is a string method that is similar to the toString()
function. Both methods are used internally in JavaScript and can be invoked automatically.
We don’t need to call it explicitly in the script. This method doesn’t change the value of the original string.
Syntax of JavaScript string.valueOf()
:
refString.valueOf();
Parameter
This method does not take any parameters.
Return
This method converts a string object into a string and returns the primitive value of a string.
Example Codes: Use the string.valueOf()
Method to Convert a String Object Into a String
In JavaScript, we create string objects to manipulate a sequence of characters. In this example, we have created a string object and will use the string.valueOf()
method to convert it into a string and get its primitive value.
const strPrim = 'string object';
const strObj = new String(strPrim);
let refValue = strObj.valueOf();
console.log(refValue);
Output:
string object
Example Codes: Use the string.valueOf()
Method to Display String Object as HTML Text
We don’t have to use a string object in the code as a string. However, a string object can be displayed as text in a document using the string.valueOf()
method.
In the example below, we have created a string object and used the string.valueOf()
method to check the output.
let str = new String("This is a paragraph.");
let restr = str.valueOf();
console.log(restr);
Output:
This is a paragraph.
The string.valueOf()
method is supported in most modern browsers. This method can help users get a string object displayed as HTML text.