Javascript Strings

JavaScript strings are used to storing and manipulating text or characters. Or The JavaScript string is an object that represents a sequence of characters.

Javascript string can be created by 2 ways –


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>

Output:-


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.

Let’s have the example to create a string in JavaScript by new keyword.

Input:-
<script>  
   var mystring =new String("hello your text ");  
   document.write(mystring);  
</script>

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

         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>

Output:-


Escape character

Because strings must be written within single or double quotes, JavaScript will misunderstand below string:-

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:

CodeResulltDescription
\’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:

CodeResullt
\bBackspace
\fForm Feed
\nNew Line
\rCarriage Return
\tHorizontal Tabulator
\vVertical 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 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)