(click anywhere to close)
OPEN MENU

[JavaScript] Strings

category: Website | course: JavaScript | difficulty:

Strings support any character you want to give it, as it is capable of displaying all kinds of text. But, some of the characters are reserved, like the quotes around the string itself. You can’t use them like you normally would, because they would signal the end of the string.

var someString = "So I said to John,"Hey, what are you doing?!", but he just looked away."; //ERROR

Escaping

To use a special character within a string, you need to escape it, which simply means adding a backslash ( ) in front of it. These are all the special characters:

Escape Character

Description

\’

Single quote

\”

Double Quote

\\

Backslash

\n

New Line

\r

Carriage Return

\t

Tab

\b

Backspace

\f

Form Feed

console.log("Line\nNew Line");
/* Prints:
Line
New Line
*/

The last three are not that useful on the web, and you’ll probably never need them. Good to know they exist though.

Converting Numbers to Strings

We’ve already seen how to convert strings to numbers. The other way around has more methods, as you can decide which notation to use.

Method

Description

toString()

Converts full number to a String.

toExponential(arg)

Writes number using scientific notation, using arg numbers behind the decimal point.

toFixed(arg)

Writes number using arg decimals

toPrecision(arg)

Writes number with length of arg numbers

var x = 100;
console.log(x.toString()); //Prints "100"
console.log(x.toExponential(0)); //Prints "1e+2"
console.log(x.toFixed(4)); //Prints "100.0000"
console.log(x.toPrecision(2)); //Prints "1.0e+2"

The toString() method actually works for all data types, but is most useful for numbers. Also, next chapter will showcase some methods for stringification that are slightly faster for numbers.

String Length

All strings have one property, which is length. It returns the amount of characters within the String – which means including white space.

var x = "Hello World!";
console.log(x.length); //Prints 12
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)