JavaScript String Methods

20 JavaScript String Methods with examples

Introduction

JavaScript String Methods help you to work with Strings. Here are various helper methods to work with a series of characters.

Note: All JavaScript String Methods return new a string. They do not change the original string.

Find String Length

The JavaScript length property returns the length of any string for example.

// Example
let myString = "This is a string";
let string_length =  myString.length;
console.log(string_length)
// output 16

Finding a specific text

The indexOf() method

 This method returns the position of the first occurrence of a specified text in a string.

Note: JavaScript always counts from zero.

Below the example shows the position of “JavaScript”.

// Example, indexOf()
let my_string = "I am learning JavaScript";
let str_position = my_string.indexOf("JavaScript");
console.log(str_position);
//output  14

If The string is not found then it returns -1

// Example, if string not found.
let my_string = "I am learning JavaScript";
let str_position = my_string.indexOf("C Language");
console.log(str_position);
//output  -1

The lastIndexOf() method

This method returns the position of the last occurrence of a specified text in a string. It returns -1 if the specified text is not found.

The example shows the position of “JavaScript”.

//Example, lastIndexOf()
let my_string = "we are learning JavaScript language, and JavaScript is easy to understand";
let str_position = my_string.lastIndexOf('JavaScript');
console.log(str_position);
//output 41

Parameters of indexOf() & lastIndexOf() methods.

The indexOf() and lastIndexOf() method accepts 2nd parameter as starting position for the search.

They both search the specified text from this given position.

The basic difference between these two methods is the lastIndexOf() method searches from end to beginning (backward search) but the indexOf() method search is forward.

Searching for a specific text

search() method

With the help of the search() method, you can search for the position of a specified value and get the position.

This method is used to search for a match between a regular expression and a specified string.

// javascript string methods
let my_str = "we are learning JavaScript language.";
let str_position = my_str.search("learning");
console.log(str_position);
//output  7

How the two methods, indexOf() and search(), are not equal?

These methods are not equal because The search() method does not accept the second argument as a start position.

The indexOf() method cannot search for values on the basis of regular expressions.

Extract Part of a String

JavaScript provides three methods to extract the part of a string.

  • slice(start position, end position)
  • substring(start position, end position)
  • substr(start, length)

slice() method

This method accepts 2 parameters. The starting position and the ending position.

The ending position is not included. Consider the following example.

// javascript string methods
let str = "red, blue, green";
let str_part = str.slice(4, 9);
console.log(str_part);
//output blue

JavaScript counts from zero.

If the parameters are negative Eg. slice(-13, -6) then the position is counted from the ending of the string or given value.

//example of negative values (print blue)
// javascript string methods
let str = "red, blue, green";
let str_part = str.slice(-12, -7);
console.log(str_part);
//output blue

The slice() method returns the rest of the string if you omit the second parameter.

// javascript string methods
let str = "red, blue, green";
let str_part = str.slice(4);
console.log(str_part);
//output blue, green

If you provide a negative parameter it counts from ending and gives output as

// javascript string methods
let str = "red, blue, green";
let str_part = str.slice(-6);
console.log(str_part);
//output  green

JavaScript substring() method.

The substring accepts two parameters. It will give the same output as the slice method.

unlike the slice method, the substring method cannot accept the negative number as a parameter.

let str = "red, blue, green";
let str_part = str.substring(0,3);
console.log(str_part);
//output  red

JavaScript substr() Method

The substr() method is also similar to the slice method, but the second parameter shows the length of the string.

The output will be similar to the substring() method.

String replace() method

The replace method replaces the specified value.

We are replacing the “sentence” with “paragraph”.

The replace() method is case-sensitive. If you want to replace uppercase with lower case then you need to use a regular expression with a flag as

srting.replace('/sentence/i', 'paragraph');

The  /i  flag is used for insensitivity. Now the above code can replace ‘SENTENCE’ as well.

To replace all matches use the global match flag with a regular expression   /g 

  var text = "This is a sentence"; 
  var txt = text.replace("sentence","paragraph");
  console.log(txt);
//output: This is a paragraph

Converting the string to upper and lower case using javascript string methods

toUpperCase() method.

The toUpperCase() method converts the string to upper case.

var txt1 = "Some Text Here";
var txt2 = txt1.toUpperCase();
console.log(txt2);
//Output: SOME TEXT HERE

toLowerCase() Method

The toLowerCase() method converts the string to lowercase.

//Example
var txt1 = "SOME TEXT HERE";
var txt2 = txt1.toLowerCase();
console.log(txt2);
//Output: some text here

Join two strings into one using javascript string methods

concat() method

The concat() method works the same as the ( + ) operator in Javascript.

It joins two strings.

The first parameter is separater. you can specify space hyphens etc.

var txt1 = "TEXT ONE";
var txt2 = "text two";
var txt3 = txt1.concat(' ', txt2);
console.log(txt3);
// output: TEXT ONE text two

Remove White Space Using the trim() method

The trim method removes white space from both sides of the string. consider the following example.

//Example of js trim() method
var str_with_whitespaces = "   Hello World   ";
let trim_str = str_with_whitespaces.trim();
console.log(trim_str);
// output: Helo World

Find a Character by position, using charAt() method

The chatAt(position) method returns the character at the specified position. for example, in “Hello World” The character at ‘0’ is ‘H’.

//Example
let str = "Helo World";
let firstChar = str.charAt(0);
console.log(firstChar);
// output: H

Find Unicode of specified character

The charCodeAt() returns the Unicode value of a character at the specified position in a string.

Note that this method returns a UTF-16 code (integer between 0 and 65535).

let str = "Helo World";
let firstCharCode = str.charCodeAt(0);
console.log(firstCharCode);
// output: 72

converting a string to an array

The split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator given in the argument.

This method accepts an argument as separater. you can specify any separater for example,

var str = "one, two, three, four"; 
// split using comma as a separater
str.split(",");
//output: ["one", " two", " three", " four"]
 // Split using spaces
str.split(" "); 
//output:  ["one,", "two,", "three,", "four"]
// Split with pipe
str.split("|"); 
// the | sign is absent in the given string so you will get whole string as one element of array
//output: ["one, two, three, four"]   
//try it yourself, what if we set no separaters, as
str.split('')
// you can specify any separater

Learn more about JavaScript String Methods in Video