A Platform To Learn To Code

JAVASCRIPT STRING



Javascript String is a primitive data type that stores textual values. Example "Hello World", "John Smith" etc.

The string value must be enclosed in single quotes ( '' ) or double quotes ( "" ).

"Hello World"
'Hello World'
"My name is John Smith"
'My name is John Smith'

Example: Single quote and Double quote

Run the code

All above examples are considered to be string.


Defining String in Javascript

There are 2 ways to create string in javascript

  1. String literal
  2. Using String constructor

1. Defining String using string literal is easy and preferable. To define using this way just assign text value to the variable in either single quotes or double quotes.

Example: String Using string literal

Run the code

2. To create a string using String constructor use new keyword and pass text in the String function either single quotes or double quotes.

Example: String Using String constructor

Run the code

String Length

In javascript, String has many properties and predefined methods. We will learn about string methods in the coming chapter.

One of such properties is length property. It is used to find the length of a string.

Example: String Length

Run the code

String Concatenation

String can be concatenated using + operator between two different strings to concatenate both strings.

Example: String concatenation

Run the code

Escape Character in Javascript

Sometimes you need to show quotes in texts but when you write extra quotes then Javascript gets confused where the string ends. See the example below.

"Color of "ocean" is Blue."

The above string will be chopped at "Color of ". And will also cause an error Uncaught SyntaxError: unexpected token: identifier .

To solve the above problem use backslash escape character in the string.

Backslash character ( \ ) is an escape characters which is used to escape the character which has special meaning.

To Display Write Output
double quote ( " ) \" "
single quote ( ' ) \' '
backslash ( \ ) \\ \

Example: String escape character

Run the code

The code \' escape single quote.

Example: Single quote escape

Run the code

To escape backslash itself, write 2 backslashes together (\\).

Example: Escaping backslash

Run the code

BOX