10 JavaScript String Methods You Must Know

  • javascript
  • 172 Views
  • 8 Min Read
  • 9 May 2024

JavaScript provides several methods for manipulating strings. These include splitting strings into an array, finding the position of a character, trimming whitespace from both ends of a string, converting a string to lowercase or uppercase, removing characters from a string, and finding substrings within a string. As a JavaScript developer, it's essential for you to have a crystal clear idea about the most commonly used string methods. So, let's explore these essential JavaScript string methods, including similar ones that perform related tasks.

 

Table of Contents

 

  1. How to get position of character in string - charAt()
  2. How to find a position of specified string in string - indexOf()
  3. How to check whether a given string is included in particular string - includes()
  4. How to change a certain string's content - replace()
  5. How to extract a part of string - slice()
  6. How to convert string to an array - split()
  7. How to join or combine two or more string into one string - concat()
  8. How to determine if a string begins with a specific character or string - startsWith()
  9. How to convert string case - toUpperCase() and toLowerCase()
  10. How to remove whitespace from both side of String - trim()

 

 

How to get position of character in string - charAt()

 

In order to retrieve position of a particualr character in string, you can use charAt() method. This method returns the characters at the specified index or position in string. In JavaScript, string indexing starts from 0 at the beginning of the string and goes up to stringName.length - 1 at the end. So, the index of the first character is 0, and the index of the last character is stringName.length - 1. The charAt() method accepts a number as a parameter and returns a string value.

 

Syntax

 

string.charAt(index);

 

Example

 
var str = "How are you doing today?";

console.log("First Character is: " + str.charAt(0));
console.log("10th Character is: " + str.charAt(9));
console.log("Last Character is: " + str.charAt(str.length - 1));
 

Output

 

First Character is: H

10th Character is: o

Last Character is: ?

 

In javascript, there is a similar method to charAt() called charCodeAt(). It returns a Unicode value of the character at the specified index in the string. In Javascript, every character and number has a unique Unicode value which can be retrieved using this charCodeAt() method. For example, 'c' has a Unicode value 99 and 'r' has a Unicode value 114. This method accepts a number as a parameter and returns a number value.

 

Example

 
var str = "How are you doing today?";

console.log("First Character's Unicode value is: " + str.charCodeAt(0));
console.log("10th Character's Unicode value is: " + str.charCodeAt(9));
console.log("Last Character's Unicode value is: " + str.charCodeAt(str.length - 1));
 

Output

 

First Character's Unicode value is: 72

10th Character's Unicode value is: 111

Last Character's Unicode value is: 63

 

 

How to find a position of specified string in string - indexOf()

 

In Javascript, in order to check whether a particular substring exists within a string and to find the position of the substring, there is a method called indexOf(). This method returns the index or position of the first occurrence of the specified substring within the string. It takes a sequenced portion of string and returns an index, or the position of the first character of the portion. If a specified substring does not exist within a string, it returns -1. This method accepts a string value as a parameter and returns a number value.

 

Syntax

 
string.indexOf(substring);

 

Example

 
var str = "How are you doing today?";

console.log("First time 'H' occurs at position: " + str.indexOf("H"));
console.log("First time 'are' occurs at position: " + str.indexOf("are"));
console.log("'Z' is not there in string : " + str.indexOf("Z"));
console.log("'Doing' is not there in string : " + str.indexOf("Doing"));
console.log("'?' sign occurs at position : " + str.indexOf("?"));
 

Output

 

First time 'H' occurs at position: 0

First time 'are' occurs at position: 4

'Z' is not there in string : -1

'Doing' is not there in string : -1

'?' sign occurs at position : 23

 

The IndexOf() method starts searching from the beginning of a string and returns an index of the first occurrence of the specified string. Similarly, to check from the end of the string, there is a method called lastIndexOf(). It returns an index of the first character of the specified string that occurs last. Additionally, there is a search() method that is similar to the indexOf() method and accepts a regular expression pattern as input and returns the index of the first match of that expression.

 

Example

 
var str = "How are you doing today?";

// lastIndexOf() Method
console.log("Last time 'a' occurs at position: " + str.lastIndexOf("a"));
console.log("Last time 'are' occurs at position: " + str.lastIndexOf("are"));

// search() Method with Regular Expression
console.log("First time 'H' occurs at position : " + str.search(/H/));
console.log("'h' is not there in string : " + str.search(/h/));

 

Output

 

lastIndexOf() Method

Last time 'a' occurs at position: 21

Last time 'are' occurs at position: 4

 

search() Method

First time 'H' occurs at position : 0

'h' is not there in string : -1

 

 

How to check whether a given string is included in particular string - includes()

 

In order to determine whether a specified substring exists in a particular string, there is a method called includes(). This method returns a boolean value. If the specified substring exists, it returns true; otherwise, it returns false. This method accepts a string value as a parameter and returns a boolean value. 

 

Syntax

 
string.includes(substring);

 

Example

 
var str = "How are you doing today?";

console.log("Whether 'How' is included in string: " + str.includes("How"));
console.log("Whether 'how' is included in string: " + str.includes("how"));
console.log("Whether 'today?' is included in string: " + str.includes("today?"));
 

Output

 

Whether 'How' is included in string: true

Whether 'how' is included in string: false

Whether 'today?' is included in string: true

 

 

How to change a certain string's content - replace()

 

In Javascript, to replace a particular portion of the string, there is a method called replace(). As the name says, it replaces a particular substring with a given substring. It takes two values as a parameter. The first parameter is the string that we want to replace, and the second is the string that we want to replace it with. It only replaces the first occurrence in a string.

 

If the substring that we want to replace does not exist within a string, it returns the string as it is. It accepts string values as a parameter and also returns a string.

 

Syntax

 
string.replace(substring, updateWith);

 

Example

 
var str = "How are you doing today?";

console.log("Updated string: " + str.replace("are you", "am I"));
console.log("Updated string: " + str.replace("o", "O")); // will replace only first occurrence
console.log("Updated string: " + str.replace("?", "!"));
 

Output

 

Updated string: How am I doing today?

Updated string: HOw are you doing today?

Updated string: How are you doing today!

 

 

How to extract a part of string - slice()

 

In Javascript, in order to extract a substring from a string, you can use a method called slice(). It takes two number values as a parameter. The substring that we want to extract is specified by these parameters. The first parameter indicates the starting position, and the second parameter specifies the ending position.

 

Additionally, the slice() method can accept negative values to start extracting the substring from the end of the string. This method accepts number values as a parameter and returns a string value.

 

Syntax

 
string.slice(start, end);

 

Example

 
var str = "A Scripting and Programming language that allows you to add behaviour to web pages.";

console.log(str.slice(0, 25) + "...");
console.log(str.slice(25, 50) + "...");
console.log(str.slice(-50, -10) + "...");
 

Output

 

A Scripting and Programmi...

ng language that allows y...

age that allows you to add behaviour to ...

 

Javascirpt provides similar methods to extract a substring from a string: substr() and substring().

 

The substr() method accepts two number values as an argument. The first parameter indicates the starting position of the substring, and the second parameter indicates the length of the substring from the starting position.

 

Similarly, the substring() method also accepts two number values as arguments. These parameters indicate the starting and ending positions of the substring, respectively.  This method is identical to slice() but treats negative values as zero.

 

Example

 
var str = "A Scripting and Programming language that allows you to add behaviour to web pages.";

// substr() Method
console.log(str.substr(0, 25) + "...");
console.log(str.substr(25, 50) + "...");
console.log(str.substr(-50, 10) + "...");

// substring() Method
console.log(str.substring(0, 25) + "...");
console.log(str.substring(25, 50) + "...");
console.log(str.substring(-50, -10) + "..."); // It considers negative value as zero
 

Output

 

substr() Method

A Scripting and Programmi...

ng language that allows you to add behaviour to we...

age that a...

 

substring() Method

A Scripting and Programmi...

ng language that allows y...

...

 

 

How to convert string to an array - split()

 

In Javascript, in order to convert a string into an array, you can use the split() method. It takes a separator string as input and returns an array containing substrings separated by the specified separator. For example, using a space (" ") as the separator will split the string into an array of words.

 

Additionally, you can set a limit on the number of substrings generated by the separator. You can specify a limit as an optional parameter after the separator. So, this method accepts a string value as a parameter and returns an array value.

 

Syntax

 
string.split(separator, limit(optional));

 

Example

 
var str = "How are you doing today?";

console.log(str.split(" "));
console.log(str.split(""));
console.log(str.split("to"));
console.log(str.split(" ", 3)); // 3 is a limit argument
 

Output

 

['How', 'are', 'you', 'doing', 'today?']

['H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', ' ', 't', 'o', 'd', 'a', 'y', '?']

['How are you doing ', 'day?']

['How', 'are', 'you']

 

 

How to join or combine two or more string into one string - concat()

 

The concat() method in Javascript is used to concatenate or merge two or more strings. It takes one or more string arguments that we want to join together or combine with the original string and returns a new combined string. However, you can also use the '+' operator and template literals (`) to merge strings. This method accepts string values as a parameter and returns a string value.

 

Syntax

 

string.concat(str1, str2);

 

Example

 
var str = "How ";
var str2 = "are you ";
var str3 = "doing today";

console.log(str.concat(str2));
console.log(str.concat(str2, str3));
console.log(str.concat(str2, str3, "?"));
console.log(`${str}${str2}${str3}?`); // Using template literal (``);
 

Output

 

How are you 

How are you doing today

How are you doing today?

How are you doing today?

 

 

How to determine if a string begins with a specific character or string - startsWith()

 

In Javascript, in order to check whether a string starts with a particular substring, you can use the startsWith() method. It takes a substring as a parameter and determines whether the main string starts with it. It returns boolean values based on the input. So, this method accepts a string as a parameter and returns a boolean value.

 

Syntax

 

string.startsWith(substring);

 

 

Example

 

var str = "How are you doing today?";

console.log("This string starts with 'H': " + str.startsWith("H"));
console.log("This string starts with 'How are': " + str.startsWith("How are"));
console.log("This string starts with 'are you': " + str.startsWith("are you"));

 

Output

 

This string starts with 'H': true

This string starts with 'How are': true

This string starts with 'are you': false

 

Similar to startsWith(), Javascript also provides a method to determine whether a string ends with a particular substring, called the endsWith() method. It also accepts a string as a parameter and returns a boolean value.

 

Example

 

var str = "How are you doing today?";

console.log("This string ends with '?': " + str.endsWith("?"));
console.log("This string ends with 'day?': " + str.endsWith("day?"));
console.log("This string ends with 'today': " + str.endsWith("today"));

 

Output

 

This string ends with '?': true

This string ends with 'day?': true

This string ends with 'today': false

 

 

How to convert string case - toUpperCase() and toLowerCase()

 

In Javascript, you can change the case of the string using methods such as toUpperCase() and toLowerCase(). These methods don't require any parameters. As name says, the toUpperCase() method converts entire string into an upper case and the toLowerCase() method converts entire string into a lower case. These methods don't accept any parameters and return a string value.

 

Syntax

 

string.toUpperCase();
string.toLowerCase();

 

 

Example

 

var str = "How are you doing today?";

// toUpperCase() Method
console.log(str.toUpperCase());

// toLowerCase() Method
console.log(str.toLowerCase());

 

Output

 

toUpperCase() Method

HOW ARE YOU DOING TODAY?

 

toLowerCase() Method

how are you doing today?

 

 

How to remove whitespace from both side of String - trim()

 

In Javascript, in order to remove the extra whitespace from both ends of a string, you can use the trim() method. It does not remove whitespace within the string; it only removes space from both ends of the string. This method doesn't require any parameters and returns a trimmed string.

 

Syntax

 

string.trim();

 

Example

 

var str = "   How are you doing today?   "; // contains whitespace
var str2 = "How are you doing today?"; // does not contain whitespace

console.log(str.trim());
console.log("Both the string are equal: " + (str === str2));
console.log("Both the string are equal: " + (str.trim() === str2));

 

Output

 

How are you doing today?

Both the string are equal: false

Both the string are equal: true

 

 

Conclusion

 

So far, we've looked at the JavaScript string methods that are used the most. Along with these methods, we also compared related and similar methods. Keep practicing these methods, and you'll gain expertise with JavaScript string manipulation. If you really enjoyed reading this article, share your thoughts in the comment section.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Vanvir Singh Devda ( vanvirsinh )

Full Stack Developer | MERN Stack

Joined On 12 Feb 2024

More from Vanvir Singh Devda

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to create working responsive navbar with multilevel dropdown menu in React Js

react-js

9 Jul 2024

Have you ever found yourself stuck in the complexity of creating a working and responsive ....

Exploring What Web Developers Need to Know For The Future

web-development

17 May 2024

The entire world is experiencing a technological revolution, and web development as a crea....

 10 JavaScript String Methods You Must Know

javascript

9 May 2024

JavaScript provides several methods for manipulating strings. These include splitting stri....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

JavaScript concepts for beginner web developer

javascript

9 May 2024

This tutorial is going to be very helpful specially for beginners in JavaScript. Throughou....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....