String in JavaScript:
String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in single or double quotation marks.
Example: String literal
"Hello World"
'Hello World'
String value can be assigned to a variable using equal to (=) operator.
Example: String literal assigned to a variable
var str1 = "Hello World";
var str2 = 'Hello World';
Concatenation:
A string is immutable in JavaScript, it can be concatenated using plus (+) operator in JavaScript.
Example - String concatenation
var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher ';
A string can also be treated like zero index based character array.
Example: String as array
var str = 'Hello World';
str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o
str.length // 11
Include quotation marks inside string:
Use quotation marks inside string value that does not match the quotation marks surrounding the string value. For example, use single quotation marks if the whole string is enclosed with double quotation marks and visa-versa.
Example: Quotes in string
var str1 = "This is 'simple' string";
var str2 = 'This is "simple" string';
If you want to include same quotes in a string value as surrounding quotes then use backward slash (\) before quotation mark inside string value.
Example: Quotes in string
var str1 = "This is \"simple\" string";
var str2 = 'This is \'simple\' string';
String object:
JavaScript also provides you String object to create a string using new keyword.
Example: String object
var str1 = new String();
str1 = 'Hello World';
// or
var str2 = new String('Hello World');
In the above example, JavaScript returns String object instead of string primitive.
Caution:
Be careful while working with String object because comparison of string objects using == operator compares String objects and not the values. Consider the following example.
Example: String object comparison
var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;
str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true
typeof(str1); // object
typeof(str3); //string
Note :
It is recommended to use primitive string instead of String object.
Learn about JavaScript string properties and methods in the next section.
Points to Remember :
- JavaScript string must be enclosed in double or single quotes (" " or ' ').
- String can be assigned to a variable using = operator.
- Multiple strings can be concatenated using + operator.
- A string can be treated as character array.
- Use back slash (\) to include quotation marks inside string.
- String objects can be created using new keyword. e.g.
var str = new String();
- String methods are used to perform different task on strings.