Signup/Sign In

JavaScript Strings

In JavaScript, a String is a sequence of characters which can be alphabets, numbers, or special characters, either simply enclosed within quotes or created using the String global object. Some examples of strings are "studytonight", "study1234tonight", "1234", "@#@#", etc.

We will cover the various ways in which we can create a string in JavaScript and various operations that we can perform on JavaScript strings along with covering some of the most common and useful String built-in methods.

The String object is a wrapper class and a global object in JavaScript.

Ways to create JavaScript String

In JavaScript, basic string literals are also treated as strings and we can use the String global object's properties and methods with string literals. So we can say that JavaScript provides us with different ways of creating strings, which are:

  1. Using basic string literals or using the String constructor

  2. Using the String global object - Using the new Keyword.

The string literals are treated as primitive string type by JavaScript and are created either using string literals or using the String constructor whereas the string created using the new Keyword is treated as String object.

But JavaScript automatically converts the primitive string type to String object so that we can use the String global object properties and methods.

JavaScript String Using string literals

To create a string, we can use either a single quote or a double quote to enclose the sequence of characters. See the example below:

let str = "Studytonight";   // double quote
let newstr = 'JavaScript';   // single quote

We can also define multiline strings using concatenation, i.e. using the + operator, or using the backslash character. Let's see examples for both.

Using String Concatenation:

let longStr = "This is a long string" +
              " which is easy to define" +
              " using string concatenation" +
              " or in simple words - joining strings";

Using backslash character:

let longStr = "This is a long string \
which is easy to define \
using backslash character \
like this";

String Literal as Template Literal:

Also, after ECMAScript2015, string literals can act as Template Literals, which means a string can act as a template in which we can embed expressions using ${ } syntax. Let's take an example to see this:

let str = 'world!';

// using backticks not single quotes
document.write(`hello ${str}`);


hello world!

So these are the various ways of creating a string literal.

Creating string using String Constructor

If we have a sequence of characters or any other data type(even array) in JavaScript and we want to convert it into a string primitive type, we can use the String constructor. Following is the syntax for it:

String(anything);

Let's take an example to understand this:

In the example above, we have defined a number and an array and then converted them into a string primitive type using the String constructor. We have also used the typeof operator to verify the data type.

Using String Object

To create a new String object, we use the new keyword.

let obj = new String("studytonight");
document.write(typeof obj);


object

In the code example above we have created a new String object.

JavaScript String as character Array

JavaScript String is treated just like an array of characters and we can access its characters just like we access data stored in an array, using index value. Yes, each string character is provided an index value starting from 0.

let str = "StudyTonight"; 

let ch1 = str[0];   // Accessing using index
console.log(ch1);   // Output: S


S

Similarly, we can also iterate over the sequence of characters stored in the string.

JavaScript String: Iteration

Since the string is a sequence of characters and each character is provided an index, so we can iterate its characters using a loop in JavaScript.

let str = "hello"; 

for(let ch of str)
    console.log(ch);


h
e
l
l
o

JavaScript String Comparision

In JavaScript, we can compare string values by using comparison operators. Yes, no function is required, we can use the less than or greater than or equality operator to compare two strings in JavaScript.

let str1 = "abc";
let str2 = "abc1";

let isEqual = (str1==str2);

console.log("Are the given two strings equal: " + isEqual);


Are the given two strings equal: false

JavaScript Strings Special Characters

JavaScript Strings support quotes to be used inside of a string as long as they do not match the quotes that surround the string, for example: "this is a string 'this is quote inside a string' " this string is valid because the string is created using the double quotes and inside we have used the single quotes, but in this case, if we want to add a double quote inside the string, we will have to use an escape character.

If the same quotes are used inside and surrounding the string then the string will be chopped in half as it will consider the quote used inside the string as the ending quote, to avoid such conditions backslash escape character (\) is used as an escape character.

There are various escape notations in JavaScript:

  1. \' - To escape a single quote

  2. \" - To escape a double quote

  3. \\ - To escape a backslash itself

Then there are some special characters:

  1. \b - backspace

  2. \f - Form feed

  3. \n - Newline

  4. \r - carriage return

  5. \t - horizontal tabulator

  6. \v - vertical tabulator

Difference between String literal and String Object

Although we have explained this at the beginning, let's take a few examples to see the difference between both. When we define a string literal or a String object, as mentioned above, we can use the typeof operator to find whether a given variable stores a primitive type string or a String object.

let str = "This is a string";
let strObj = new String("This is also a string");

console.log(typeof str);
console.log(typeof strObj);


string
object

Also, when we use the eval() function, the primitive type is considered as source code where a String object is treated like just another object. Let's see an example:

let str1 = '2 + 2'              // creates a string primitive
let str2 = new String('2 + 2')  // creates a String object
console.log(eval(str1))         
console.log(eval(str2))


4
2 + 2

As you can see, the first string is evaluated as an expression, whereas the String object is simply printed as it is.

So with this, we have completed a basic introduction to JavaScript strings, covering primitive string type and String objects and some common operations like iteration, etc. In the next tutorial, we will cover the most common methods of JavaScript String type.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight