String in Javascript

Rumman Ansari   Software Engineer   2023-03-26   5599 Share
☰ Table of Contents

Table of Content:


JavaScript String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

  1. By string literal
  2. By string object (using new keyword)

1. By string literal

The string literal is created using double quotes. The syntax of creating string using string literal is given below:

var stringname="string value";

Let’s see the simple example of creating string literal.


<script>  
var str="This is string literal";  
document.write(str);  
</script>  

2. By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Let’s see the example of creating string in JavaScript by new keyword.


<script>  
var stringname=new String("hello javascript string");  
document.write(stringname);  
</script>