JavaScript strings

      No Comments on JavaScript strings

JavaScript strings are used for storing and manipulating text.

Syntax:

var val = "Value in string";

The value can be enclosed in single or double quotes.Some examples are:

  • var abc="scanfocde.com" ;
  • var name1='George bush' ;
  • var wish="Good morning" ;

String length

Length of string can be known by using inbuilt method called length.
Example:

var string="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var stringlength= string.length;

Output:

<p id='answer'></p>
<script>
var string="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var stringlength= string.length;
document.getElementById('answer').innerHTML=stringlength;
</script>

Result:


Using special characters in JavaScript strings

It may be the case that we need to put single or double quotes in a string.

var string1='We are Indian's'

The output of this will not show any results.The solution to this problem is using \ escape character.
The backslash escape character turns special characters into string characters:
For example:

<p id='answer1'></p>
<script>
 var string1='We are Indian\'s';
 document.getElementById('answer1').innerHTML=string1;
</script>

Result:

We are Indian’s

The commonly used special characters that can be inserted using the \ Escape character:

CodeOutputs
\’single quote
\”double quote
\\backslash

Some other escape characters valid in JavaScript are:

CodeOutputs
\bBackspace
\rCarriage Return
\fForm Feed
\tHorizontal Tabulator
\vVertical Tabulator

JavaScript strings

JavaScript strings as Objects

Normally. JavaScript strings are created using literals. But strings can be created as objects.

Syntax:

var val = new String(string);

Example:

<p id="anser3"></p>
<script>
var x = "Scanfcode.com";              // x is a string
var y = new String("Scanfcode.com");  // y is an object
document.getElementById("answer3").innerHTML =
"Type of x is-"+typeof x + "<br>" +"Type of y is-"+ typeof y;
</script>

Result:

Type of x is-string
Type of y is-object

Comparing strings

When compared with == strings are equal.
When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.

Example:

<p id="demo1" ></p>
<p id="demo" ></p>
<script>
var x = "Scanfcode";              // x is a string
var y = new String("Scanfcode");  // y is an object
document.getElementById("demo1").innerHTML = "Comparing variablles with == :"+(x==y);
document.getElementById("demo").innerHTML ="Comparing variablles with === :"+ (x===y);
</script>

Result:

Leave a Reply

Your email address will not be published. Required fields are marked *