Javascript Strings
In JavaScript, strings are used to represent text and are declared using quotes, either single ('
) or double ("
). Here are some important aspects of working with strings in JavaScript:
A javascript string can be created in 2 ways -
By string literal
A string literal is created by enclosing the text within double quotes ("
). Here's an example:
var myString = "your text";
You can also use single quotes ('
) to create a string literal:
var schoolName1 = "Rian International"; // Double quotes
var schoolName2 = 'DPS'; // Single quotes
Let's see the simple example of creating string literal.
Input:-
Output:-
By string object (using new keyword)
In JavaScript, a string object can be created using the new
keyword. Here's the syntax:
var myString = new String("your text");
The new
keyword is used to create an instance of the String
object. However, using the string literal syntax ("your text"
) is generally preferred over creating string objects with the new
keyword.
Here's an example that demonstrates creating a string in JavaScript using the new
keyword:
Input:-
Output:-
Note:- Don't create strings as objects. It slows down execution speed. The new keyword complicates the code. This can produce some unexpected results.
String Length
You can determine the length of a string using the length
property.
Input:-
Output:-
Escape character
Because strings must be written within single or double quotes, JavaScript will misunderstand the below string:-
var x = "I have a pet named "maggi" since 2 years.";
The string will be cut to "I have a pet named ".
To avoid this problem, we need to use the backslash escape character.
The backslash () escape character replaces special characters into string characters:
Code |
Resullt |
Description |
' |
' |
Single quote |
" |
" |
Double quote |
\ |
|
Backslash |
So now the above string will become like given below:-
var x = "I have a pet named "maggi" since 2 years.";
There are six other escape sequences are valid in JavaScript:
Code |
Resullt |
|
Backspace |
|
Form Feed |
|
New Line |
|
Carriage Return |
|
Horizontal Tabulator |
|
Vertical Tabulator |
Note:- The 6 escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.
Equal operator for string literal and string object
var x = "Charlie";
var y = new String("Charlie");
For the above two strings (x == y) is true because x and y have equal values
But for (x === y) it will be false because x and y have different types (string and object)