By string literal
The string literal is created by using double quotes(“). Below is the example to creating string using string literal:
var mystring = "your text";
We can use single or double quotes:
var schoolName1 = "Rian Internation"; // Double quotes var schoolName2 = 'DPS'; // Single quotes
Let’s see the simple example of creating string literal.
Input:- <script> var mystring ="This is string literal text"; document.write(mystring); </script>
By string object (using new keyword)
Below is the syntax to create string object using new keyword:
var mystring = new String("your text");
Here, new keyword is used to create instance of string.
Input:- <script> var mystring =new String("hello your text "); document.write(mystring); </script>
Note:- Don’t create strings as objects. It slows down execution speed. The new keyword complicates the code. This can produce some unexpected results.
To identify the length of a string, use the built-in method length.
Input:- <script> var myString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var len = myString.length; document.write(len); </script>
var x = "I have a pet named "maggi" since 2 years.";
The string will be chopped or cut to “I have a pet named “.
To avoid this problem, we need to use the backslash escape character.
The backslash (\) escape character replace special characters into string characters:
So now the above string will become like given below:-
var x = "I have a pet named \"maggi\" since 2 years.";
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 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)