JavaScript String.valueOf() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript string.valueOf():
  2. Example Codes: Use the string.valueOf() Method to Convert a String Object Into a String
  3. Example Codes: Use the string.valueOf() Method to Display String Object as HTML Text
JavaScript String.valueOf() Method

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.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript String