JavaScript String Operation

JavaScript String Operation

A JavaScript String is zero or more characters written within quotes. We can perform following operations on string:

Operation Description Example
String Length We can get length of any string stored in a variable.

Syntax: var.length

Here, var can be any variable.

var txt = “Gargi”;
var sln = txt.length;

Output: 5

Finding a String in a String We can get index (position) of a text in a string.


indexOf(): Returns first occurrence of the text

lastIndexOf():Returns last occurrence of the text

var str = “You will locate me!”;
var pos = str.indexOf(“locate“);

Output: 9

Slice (start, end) It extracts a part of a string and returns the extracted part in a new string. It takes two parameters: the starting position and the end position [excluding the end position value] var str = “I am Rudra!”;

var res = str.slice(5, 10);

Output: Rudra

Substring (start, end) It is similar to slice(), but it cannot accept negative indexes unlike slice operation. var str = “I am Rudra!”;

var res = str. substring (5, 10);

Output: Rudra

Substr (start, length) It is similar to slice(). Here, the second parameter is the length of the text to be extracted. var str = “I am Rudra!”;

var res = str. substr(5, 10);

Output: Rudra!

Replace () It replaces a specified value with another value in a string.

It is case sensitive and replaces only the first finding. It doesn’t change the original but returns the change into a new variable.

var str = “I am German”;

var n = str.replace(“German”, “Indian”);

Output: I am Indian

Converting Case To convert a case, we can use the following:

1. toUpperCase()

2. toLowerCase()

var text = “Hello World!”;

var uText = text.toUpperCase();

var ltext = text.toLowerCase();

Concat () It joins two or more strings together. var text1 = “Hello”;

var text2 = “India”;

var text3 = text1.concat(” “, text2);

Trim () It removes whitespaces from both side of a given string. var str = ”       Hello India       “;


Split () It splits a string based on a condition mentioned within the brackets. var txt = “a,b,c,d,e”;

txt.split(“,”); // Split on commas

txt.split(” “); // Split on spaces

txt.split(“|”);// Split on pipe

txt.split(“”);// Split in characters


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.