Home  >  Article  >  Web Front-end  >  How to convert string in JavaScript

How to convert string in JavaScript

WBOY
WBOYOriginal
2023-05-21 09:37:376669browse

In JavaScript programming, processing strings is a very basic task. In JavaScript, there are many ways to convert strings. Below I will introduce you to four methods of string conversion in JavaScript.

Method 1: Use the String() function

Using the String() function is the most common method to convert other types of variables into string types. The code implementation of this method is very simple, just add String() before the variable to be converted. For example:

var num = 123;
var str = String(num);
console.log(typeof str); // string

Method 2: Use toString() function

toString() is one of the most basic methods in JavaScript. This method can convert number, boolean, array, object, etc. into String. Similarly, just add toString() after the variable to be converted. For example:

var num = 123;
var str = num.toString();
console.log(typeof str); // string

Method 3: Use '' or "" to enclose variables

Even if the variables enclosed with '' or "" are numbers, they will be automatically converted into strings:

var str1 = 'abcdef';
var str2 = "abcdef";
console.log(typeof str1, typeof str2); // string string

var num = 123;
var str = '' + num;
console.log(typeof str); // string

Method 4: Use the escape character '' and add character encoding

Some characters in strings in JavaScript are invisible. For example, carriage return and line feed characters, the escape characters in JavaScript are '' and '
'. In order to represent these characters in a string, an encoding for the escaped characters is required. For example:

var str1 = 'line 1
line 2
line 3';
var str2 = 'hello\world';
console.log(str1, str2);

The above are four commonly used string conversion methods in JavaScript. You can choose the appropriate method based on your needs.

The above is the detailed content of How to convert string in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn