The Talent500 Blog
20 JavaScript Essential String Methods to Ace Your Next Interview 1

20 JavaScript Essential String Methods to Ace Your Next Interview

A string is one of the most fundamental and important elements in any programming language. So taking this into account, in this article we are going to take a closer look at 20 JavaScript string methods that will help you crack your next interview.

It is a comprehensive guide that provides an overview of various string methods in JavaScript that can be used to manipulate and work with strings. This article begins by explaining the basics of strings in JavaScript, including how to declare and initialize them.

Then dives into the 20 most commonly used string methods in JavaScript, explaining how each method works, its syntax, and its use cases. The methods covered in the article include: slice(), trim(), toLowerCase(), toUpperCase(), startsWith(), endsWith(), repeat(), substring(), concat(), valueOf(), split(), replaceAll(), indexOf(), charCodeAt(), charAt(), includes(), lastIndexOf(), fromCharCode(), padEnd(), and padStart(), So without further ado let’s get into the blog:)

Overview

A string is a data type in JavaScript that represents a sequence of characters. It is used to store and manipulate text data in a program. 

Strings in JavaScript are immutable, which means that once a string is created, its contents cannot be changed. However, it is possible to create a new string based on the original string by using several string methods.

In JavaScript, strings are enclosed in single quotes, double quotes, or backticks as well. For example,

const name1 = John;

const name2 = Jane;

const name3 = `Jack`;

All three variables store the same type of data, which is a string. However, the backticks are used to create template literals, which allow us to calculate variables and expressions in a program. Now, on these strings, we can modify them using the built-in JavaScript methods.

slice() Method

The slice() method is a built-in method that allows us to extract a piece of a string and return a new string without changing the original string. It takes two arguments: the start index and the end index of the portion of the string that we want to extract.

The syntax for the slice() method is as follows:

str.slice(startIndex, endIndex);

Syntax explained:

  • startIndex: It is the starting index of the string from which we want to extract the string.
  • endIndex: It is the index at which the extraction will end. But the last index will not be included in the result. If the endIndex is not specified, the slice method will extract the rest of the string starting from the startIndex.

// SLICE METHOD

let str = Ajay Yadav;

console.log(str.slice()); //Ajay Yadav

console.log(str.slice(0, 4)); //Ajay

console.log(str.slice(NaN, 4)); //Ajay

console.log(str.slice(5)); //Yadav

console.log(str.slice(9, 3)); //NOTHING

console.log(str.slice(5, 1)); //Yada

console.log(str.slice(1, 5)); //NOTHING

console.log(str.slice(NaN, 5)); //Ajay

Some key points that should be kept in mind while using the slice() method are:

  • It returns nothing or empty if the start index is bigger than the last index.
  • The slice method treats the NaN parameter as a zero.
  • When we pass a negative parameter to the slice method, then it goes backwards from the end of the string to find the index.

trim() Method

The trim() method is used to remove any whitespace characters from both the beginning and end of a string. It does not modify the original string but rather returns a new string with the whitespace removed.

// TRIM METHOD

let str =   Ajay Yadav      ;

console.log(str.trim()); //Ajay Yadav

console.log(str.trimEnd()); //    Ajay Yadav

console.log(str.trimStart()); //Ajay Yadav

To remove whitespace from the beginning and from the end of the string, we can use their respective methods, which are trimStart() and trimEnd().

toLowerCase() Method

The toLowerCase() method is used to return a new string with all the characters of the original string converted to lowercase letters.

// TOLOWERCASE METHOD

let str = AJAY YADAV;

console.log(str.toLowerCase()); //ajay yadav

str = Ajay yadAV;

console.log(str.toLowerCase()); //ajay yadav

str = null;

console.log(str.toLowerCase()); //TypeError: Cannot read property ‘toLowerCase’ of null

But please keep in mind that if the string is undefined or null, then we will get an error.

toUpperCase() Method

The toUpperCase() method is used to return a new string with all the characters of the original string converted to uppercase letters.

// TOUPPERCASE METHOD

str = ajay yadaV;

console.log(str.toUpperCase()); //AJAY YADAV

str = Ajay yadav;

console.log(str.toUpperCase()); //AJAY YADAV

str = null;

console.log(str.toUpperCase()); //TypeError: Cannot read property ‘toUpperCase’ of null

This method will also return an error if the string is undefined or null.

startsWith() Method

The startsWith() method is used to check if a string starts with a particular substring. It returns a boolean value (true or false) depending on whether the original string begins with the provided substring.

This the following syntax of the method:

str.startsWith(searchString, position);

It takes one or two arguments;

  • searchString: This is the required argument and represents the substring we want to check at the beginning of the original string. It can be a string or a regular expression as well.
  • position: This is an optional argument and represents the starting position within the original string where the search will start. If not specified, the default value will be 0, which is the beginning of the string.

// STARTSWITH METHOD

let str = Ajay Yadav;

console.log(str.startsWith(A)); //true

console.log(str.startsWith(Ajay)); //true

console.log(str.startsWith(AJAY)); //false

console.log(str.startsWith(Y, 5)); //true

console.log(str.startsWith(Y, 4)); //false

endsWith() Method

The endsWith() method is used to check if a string ends with a specified substring. It returns a boolean value (true or false) depending on whether the original string ends with the provided substring.

This the following syntax of the endsWith() method:

str.endsWith(searchString, length);

The endsWith() method takes one or two arguments:

  • searchString: This is the required argument and represents the substring we want to check at the end of the original string. It can be a string or a regular expression as well.
  • length: This is an optional argument and represents the number of characters from the end of the original string where the search should end. If not specified, its default value will be the length of the original string.

// ENDSWITH METHOD

let str = Ajay Yadav;

console.log(str.endsWith(v)); //true

console.log(str.endsWith(Yadav)); //true

console.log(str.endsWith(V)); //false

console.log(str.endsWith(YADAV)); //false

console.log(str.endsWith(yadav”,5)); //false

repeat() Method

The repeat() method is used to create a new string by repeating an existing string a specific number of times. It returns a new string that contains the original string repeated a specific number of times.

This is the following syntax of the repeat() method, and it takes one argument:

str.repeat(count);

  • count: This is the required argument and represents the number of times that an original string should be repeated. It must be a non-negative integer value.

 

// REPEAT METHOD

str = Ajay;

console.log(str.repeat(0)); //nothing

console.log(str.repeat(5)); //Repeat 5 times “Ajay”

console.log(str.repeat(6.333)); //Repeat 6 times “Ajay”

console.log(str.repeat(8)); //RangeError: Invalid count value

Some key points that should be kept in mind while using the slice() method are:

  • It returns the copied version of the original string.
  • We can pass an integer number between 0 and any number of positive integers to repeat the string.
  • If we pass the negative number, then we will get a “Range Error” as an output.
  • Also, we can pass a fractional number, and it will round that fraction to the nearest integer.

substring() Method

The substring() method is used to extract a portion of a string and create a new string from it. It returns a new string that consists of a particular part of the original string, starting from a specified index and ending before a specified index.

This is the following syntax of the substring() method:

str.substring(start, end);

Syntax explained:

  • start: This is the required argument and represents the starting index of the substring. It must be a non-negative integer value.
  • end: This is the optional argument and represents the ending index of the substring. The substring does not include the character at the ending index. If this argument is omitted, the substring includes all characters from the starting index to the end of the string.

 

// SUBSTRING METHOD

let str = Ajay Yadav;

console.log(str.substring()); //Ajay Yadav

console.log(str.substring(0, 4)); //Ajay

console.log(str.substring(0)); //Ajay Yadav

console.log(str.substring()); //Ajay Yadav

console.log(str.substring(1, 4)); //Ajay

console.log(str.substring(1, 5)); //nothing

console.log(str.substring(5, 1)); //nothing

console.log(str.substring(NaN, 1)); //nothing

console.log(str.substring(9, 3)); //y Yada

The following are important points to remember: 

  • If the starting parameter is greater than the last parameter, then it swaps the order of the parameters.
  • It treats negative parameters as zero.

concat() Method

The concat() method is used to concatenate two or more strings and create a new string from them. It returns a new string that is the result of appending one or more strings to the end of the original string.

This method takes one or more arguments, which are the strings to be concatenated to the original string. It can be either string literals or string variables, and we can pass as many arguments as we want to concatenate.

str.concat(string1, string2, …, stringN);

Here, string1, string2, and stringN are the strings that will be concatenated with the original string.

// CONCAT METHOD

const firstName = Ajay;

const lastName = Yadav;

console.log(firstName.concat( , lastName)); //Ajay Yadav

console.log(firstName.concat(Kumar)); //AjayKumar

console.log(firstName.concat(Kumar, Yadav, From, India)); //AjayKumarYadavFromIndia

Some key points:

  • The concat() method is used to merge two or more strings and returns a new string.
  • We can join as many strings as we want to the original string.

valueOf() Method

The valueOf() method is used to return the primitive value of a string object. It does not take any arguments and does not modify the original string object. It simply returns the primitive value representation of the string object on which it is called.

// VALUEOF METHOD

let str = new String(Ajay Yadav);

console.log(typeof str); //object

console.log(str.valueOf()); //Ajay Yadav

console.log(typeof str.valueOf()); //string

split() Method

The split() method is used to split a string into an array of substrings based on a defined separator. An array of substrings is returned by splitting the original string at occurrences of the defined separator.

Here is the syntax for the split() method, which accepts two parameters:

str.split(separator, limit);

Syntax explained:

  • separator: A string that specifies the separator at which the string should be split. This can be a simple string or a regular expression pattern.
  • limit: An optional integer that specifies the maximum number of substrings to include in the resulting array. If this parameter is omitted, all possible substrings will be included in the array.

// SPLICE METHOD

let str = Ajay Yadav;

console.log(str.split( )); //[“Ajay”, “Yadav”]

console.log(str.split( , 1)); //[ ‘Ajay’ ]

console.log(str.split(“”)); //[“A”, “j”, “a”, “y”, ” “, “Y”, “a”, “d”, “a”, “v”]

Some key points:

  • It is used to divide a string into an array by a separator.
  • If we omit the separator then it returns the entire string.

replaceAll() Method

The replaceAll() method is used to replace all occurrences of a specific substring pattern within a given string. It takes two arguments: the first argument is the substring pattern to be replaced, and the second argument is the string or function to replace it with.

It does not change the original method; instead, the repaceAll() method returns a new string with all the replacements made.

// REPLACEALL METHOD

let str = Ajay Yadav, Ajay Ajay Ajay;

console.log(str.replaceAll(Ajay, Prince)); //Prince Yadav, Prince Prince Prince

indexOf() Method

The indexOf() method is used to find the index of the first occurrence of a particular substring within a given string. This method takes one required argument, which is the substring to search for within the string. But we can also pass an optional argument to specify the starting index of the search.

// INDEXOF METHOD

let str = Ajay Yadav;

console.log(str.indexOf(j)); //1

console.log(str.indexOf(Y, 6)); //-1 (none)

console.log(str.indexOf(Y, 4)); //5

charCodeAt() Method

The charCodeAt() method is used to return the Unicode value of the character at a specified index within a given string. This method takes one required argument, which is the index of the character to retrieve the Unicode value.

// CHARCODEAT METHOD

let str = Ajay Yadav;

console.log(str.charCodeAt(0)); //65

console.log(str.charCodeAt(1)); //106

console.log(str.charCodeAt(1)); //NaN

charAt() Method

The charAt() method is used to return the character at a specified index within a given string. It takes one required argument, which is the index of the character to retrieve.

// CHARAT METHOD

let str = Ajay Yadav;

console.log(str.charAt(0)); //A

console.log(str.charAt(99)); //nothing

console.log(str.charAt(2)); //nothing

includes() Method

The includes() method is used to check if a given string contains a particular substring. This method takes one required argument, which is the substring to search for within the string. However, we can also pass an optional argument to specify the starting index of the searching string.

It returns true if the desired substring is found; otherwise, it returns false as an output.

// INCLUDES METHOD

str = Ajay Yadav;

console.log(str.includes(Ajay)); //true

console.log(str.includes(Ajay, 1)); //false

console.log(str.includes(Ajay, 0)); //true

console.log(str.includes(5)); //false

console.log(str.includes(true)); //false

console.log(str.includes([A, H])); //false

lastIndexOf() Method

The lastIndexOf() method is used to return the index of the last occurrence of a specified substring within a given string. This method takes one required argument, which is the substring to search for within the string. However, we can also pass an optional second argument to specify the end index of the search string.

// LASTINDEXOF METHOD

let str = Ajay Yadav;

console.log(str.lastIndexOf(a)); //8

console.log(str.lastIndexOf()); //-1

console.log(str.lastIndexOf(a, 6)); //6 (it will find the last item between 0 – 6)

console.log(str.lastIndexOf(Ajay, 8)); //0

console.log(str.lastIndexOf(Hello)); //-1

fromCharCode() Method

The fromCharCode() method is used to create a string from a sequence of Unicode values. This method takes one or more numeric arguments that represent Unicode values and returns a string containing the characters represented by the Unicode values.

let str = Ajay Yadav;

console.log(str.charCodeAt(0)); //65

console.log(str.charCodeAt(1)); //106

console.log(str.charCodeAt(2)); //97

console.log(str.charCodeAt(3)); //121

// FROMCHARCODE METHOD

console.log(String.fromCharCode(65)); //A

console.log(String.fromCharCode(106)); //j

console.log(String.fromCharCode(97)); //a

console.log(String.fromCharCode(121)); //y

// Pass the multiple arguments

console.log(String.fromCharCode(65, 106, 97, 121)); //Ajay

padStart() Method

The padStart() method is used to pads(inserts) the beginning of a string with another string until the desired length is reached. The method takes two arguments: the first argument specifies the total length of the resulting string, and the second argument is the string that should be used to pad the beginning of the original string.

If the second argument is not provided, then this method will use a space character as the default padding character. If the length of the original string is greater than or equal to the specified length, the method will return the original string without any padding.

// PADSART METHOD

let str = Yadav;

console.log(str.padStart()); //Yadav

console.log(str.padStart(6)); // Yadav

console.log(str.padStart(10, .)); //…..Yadav

console.log(str.padStart(10, Ajay )); //Ajay Yadav (total length of the string is 10)

padEnd() Method

The padEnd() is used to pads(inserts) the end of a string with another string until the desired length is reached. This method takes two arguments: the first argument specifies the total length of the resulting string, and the second argument is the string that should be used to pad the end of the original string.

If the second argument is not provided, it will use a space character as the default padding character. If the length of the original string is greater than or equal to the specified length, the method will return the original string without any padding.

// PADEND METHOD

let str = Ajay;

console.log(str.padEnd()); //Ajay

console.log(str.padEnd(6)); //Ajay

console.log(str.padEnd(8, .)); //Ajay….

console.log(str.padEnd(10, Yadav)); //Ajay Yadav

(Total length of the string is 10)

To summarize 

  1. slice(): It is used to extract a piece of the string and return a new one.
  2. trim(): It is used to remove whitespaces from the string.
  3. toLowerCase(): It converts all letters in the string to lowercase.
  4. toUpperCase(): It converts all letters in the string to uppercase.
  5. startsWith(): It checks if a string starts with a particular substring.
  6. endsWith(): It checks if a string ends with a particular substring.
  7. repeat(): It repeats the string a specific number of times.
  8. substring(): It extracts a certain portion of the string.
  9. concat(): It concatenates two or more strings.
  10. valueOf(): It returns a primitive value from a string object.
  11. split(): It is used to split a string into an array.
  12. replaceAll(): It is used to replace all occurrences of a specific part of a string.
  13. indexOf(); It is used to find the index of the first occurrence.
  14. charCodeAt(): It is used to return the Unicode value of the given character.
  15. charAt(): It returns the character at a given index.
  16. includes(): It is used to check if a given string contains a particular substring.
  17. lastIndexOf(): It returns the index of the last occurrence of a defined substring.
  18. fromCharCode(): It creates a new string using the Unicode values.
  19. padStart(): It is used to insert a substring at the beginning of the string.
  20. padEnd(): It is used to insert a substring at the end of the string.

Conclusion

In conclusion, JavaScript provides a variety of string methods that can be used to manipulate and play with strings in various ways. These methods include functions for finding and replacing text, changing cases, trimming whitespace, splitting strings into arrays, and many more. By using these methods, developers can create more efficient and effective code for handling strings in their JavaScript applications. It is important to note that there are many more string methods available in JavaScript than the ones covered in this article, and developers should continue to explore and learn about them in order to become proficient in working with strings in their projects. However, these are some great string methods that will help you to ace your JavaScript interview.

Also, if you are looking for a JavaScript job, so please search them on talent500.co

2+
Ajay Yadav

Ajay Yadav

I am a frontend developer and am eager to deep dive into the technologies through my content.

Add comment