Open In App

JavaScript String Methods

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing.

JavaScript string methods are used to represent and manipulate Strings in JavaScript. There are many string methods available in JavaScript like, charAt(), toUppercase(), concat(), etc. All these functions simplify various tasks for developers, and in this tutorial, we will be looking at some JavaScript string methods one should know.

Basic JavaScript String Methods

JavaScript provides several built-in methods and properties for working with strings. Below is the list of JavaScript string functions that you need to know, for mastering JavaScript strings.

JavaScript slice() Method

JavaScript slice method extracts a part of the string based on the given stating-index and ending-index and returns a new string.

Example: This example describes the JavaScript String slice() method.

JavaScript
// Define a string variable 
let A = 'Geeks for Geeks';

// Use the slice() method to extract a substring
let b = A.slice(0, 5);
let c = A.slice(6, 9);
let d = A.slice(10);

// Output the value of variable
console.log(b);
console.log(c);
console.log(d);

Output
Geeks
for
Geeks

Explanation:

The code initializes a string A with the value “Geeks for Geeks”. It then uses the slice() method to extract substrings b, c, and d from A based on specified start and end indices and prints them individually.

JavaScript substring() Method

JavaScript substring() method returns the part of the given string from the start index to the end index. Indexing starts from zero (0).

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable
let str = "Mind, Power, Soul";

// Use the substring() method to extract a substring 
let part = str.substring(6, 11);

// Output the value of variable
console.log(part);

Output
Power

Explanation:

The code initializes a string str with the value “Mind, Power, Soul”. It then uses the substring() method to extract a substring starting from index 6 and ending before index 11 (excluding the character at index 11). The extracted substring “Power” is stored in the variable part, and then it is printed to the console.

JavaScript substr() Method

JavaScript substr() method This method returns the specified number of characters from the specified index from the given string. It extracts a part of the original string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 'str'
let str = "Mind, Power, Soul";

// Use the substr() method to extract a substring f
let part = str.substr(6, 5);

// Output the value of variable
console.log(part);

Output
Power

Explanation:

The code initializes a string str with the value “Mind, Power, Soul”. It then uses the substr() method to extract a substring starting from index 6 and including the next 5 characters. The extracted substring “Power” is stored in the variable part, and then it is printed to the console.

JavaScript replace()

JavaScript replace() method replaces a part of the given string with another string or a regular expression. The original string will remain unchanged.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 'str' 
let str = "Mind, Power, Soul";

// Use the replace() method to replace the substring
let part = str.replace("Power", "Space");

// Output the resulting string after replacement
console.log(part);

Output
Mind, Space, Soul

Explanation:

The code initializes a string str with the value “Mind, Power, Soul”. It uses the replace() method to replace the first occurrence of the substring “Power” with “Space”. The modified string is stored in the variable part, and then it is printed to the console.

JavaScript replaceAll()

JavaScript replaceAll() method returns a new string after replacing all the matches of a string with a specified string or a regular expression. The original string is left unchanged after this operation.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 'str'
let str = "Mind, Power, Power, Soul";

// Use the replaceAll() method to replace all occurrences
//of "Power" with "Space" in the string 'str'
let part = str.replaceAll("Power", "Space");

// Output the resulting string after replacement
console.log(part);

Output
Mind, Space, Space, Soul

Explanation:

The code initializes a string str with the value “Mind, Power, Power, Soul”. It then uses the replaceAll() method to replace all occurrences of the substring “Power” with “Space”. The modified string is stored in the variable part, and then it is printed to the console.

JavaScript toUpperCase()

JavaScript toUpperCase() method converts all the characters present in the String to upper case and returns a new String with all characters in upper case. This method accepts single parameter stringVariable string that you want to convert in upper case.

Example: This example describes the JavaScript String toUpperCase() method.

JavaScript
// Define a string variable
let gfg = 'GFG ';

// Define another string variable 
let geeks = 'stands-for-GeeksforGeeks';

// Convert the string 'geeks' to uppercase using the toUpperCase() method
console.log(geeks.toUpperCase());

Output
STANDS-FOR-GEEKSFORGEEKS

Explanation:

The code initializes two strings, gfg and geeks. It then uses the toUpperCase() method on the string object geeks. This method converts all characters in the string to uppercase and returns the modified string. Finally, it prints the uppercase version of the geeks string to the console.

JavaScript toLowerCase()

JavaScript toLowerCase() method converts all the characters present in the so lowercase and returns a new string with all the characters in lowercase.

Example: This example describes the JavaScript String toLowerCase() method.

JavaScript
// Define a string variable
let gfg = 'GFG ';

// Define a string variable 
let geeks = 'stands-for-GeeksforGeeks';

// Convert the string 'geeks' to lowercase using the toLowerCase() method
console.log(geeks.toLowerCase());

Output
stands-for-geeksforgeeks

Explanation:

The code initializes two strings, gfg and geeks. It then uses the toLowerCase() method on the string object geeks.

JavaScript concat() Method

JavaScript concat() method method combines the text of two strings and returns a new combined or joined string. To concatenate two strings, we use the concat() method on one object of string and send another object of string as a parameter. This method accepts one argument. The variable contains text in double quotes or single quotes.

Example: This example describes the JavaScript String concat() method.

JavaScript
let gfg = 'GFG ';
let geeks = 'stands for GeeksforGeeks';

// Accessing concat method on an object
// of String passing another object 
// as a parameter
console.log(gfg.concat(geeks));

Output
GFG stands for GeeksforGeeks

Explanation:

The code initializes two strings, gfg and geeks. It then uses the concat() method on the string object gfg, passing geeks as a parameter. The concat() method concatenates the string geeks to the end of gfg, and the resulting string is printed to the console.

JavaScript trim() Method

JavaScript trim() method is used to remove either white spaces from the given string. This method returns a new string with removed white spaces. This method is called on a String object. This method doesn’t accept any parameter.

Example: This example describes the JavaScript String trim() method.

JavaScript
let gfg = 'GFG    ';
let geeks = 'stands-for-GeeksforGeeks';

// Storing new object of string
// with removed white spaces
let newGfg = gfg.trim();

// Old length
console.log(gfg.length);

// New length
console.log(newGfg.length)

Output
7
3

Explanation:

The code initializes two strings, gfg and geeks. It then uses the trim() method to remove leading and trailing whitespace from the string gfg, storing the result in newGfg. The code prints the lengths of the original string gfg (including whitespace) and the trimmed string newGfg (excluding whitespace) to the console.

JavaScript trimStart() Method

JavaScript trimStart() method removes whitespace from the beginning of a string. The value of the string is not modified in any manner, including any whitespace present after the string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 
let str = "  Soul";

// Output the original value of the string 
console.log(str);

// Use the trimStart() method to remove leading whitespace from the string 'str'
let part = str.trimStart();

// Output the resulting string after removing leading whitespace
console.log(part);

Output
  Soul
Soul

Explanation:

The code initializes a string variable str with the value ” Soul”. It prints the string to the console. Then, it uses the trimStart() method to remove leading whitespace from the string. Finally, it prints the trimmed string part to the console. The first console.log() prints ” Soul”, and the second prints “Soul”.

JavaScript trimEnd() Method

JavaScript trimEnd() method removes white space from the end of a string. The value of the string is not modified in any manner, including any white-space present before the string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 
let str = "Soul  ";

// Output the original value of the string 'str'
console.log(str);

// Use the trimEnd() method to remove trailing whitespace from the string 'str'
let part = str.trimEnd();

// Output the resulting string after removing trailing whitespace
console.log(part);

Output
Soul  
Soul

Explanation:

The code initializes a string variable str with the value “Soul “. It prints the string to the console. Then, it uses the trimEnd() method to remove trailing whitespace from the string. Finally, it prints the trimmed string part to the console. The first console.log() prints “Soul “, and the second prints “Soul”.

JavaScript padStart() Method

JavaScript padStart() method pad a string with another string until it reaches the given length. The padding is applied from the left end of the string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 
let stone = "Soul";

// Use the padStart() method to add padding characters "Mind "
//to the beginning of the string 'stone' 
stone = stone.padStart(9, "Mind ");

// Output the resulting string after padding
console.log(stone);

Output
Mind Soul

Explanation:

The code initializes a string variable stone with the value “Soul”. It then uses the padStart() method to pad the string with spaces or a specified string (“Mind “) until the resulting string reaches a length of 9 characters. Finally, it prints the modified string to the console, resulting in “Mind Soul”.

JavaScript padEnd() Method

JavaScript padEnd() method pad a string with another string until it reaches the given length. The padding is applied from the right end of the string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
// Define a string variable 
let stone = "Soul";

// Use the padEnd() method to add padding characters
//" Power" to the end of the string 'stone' 
stone = stone.padEnd(10, " Power");

// Output the resulting string after padding
console.log(stone);

Output
Soul Power

Explanation:

The code initializes a string variable stone with the value “Soul”. It then uses the padEnd() method to pad the string with spaces or a specified string (” Power”) until the resulting string reaches a length of 10 characters. Finally, it prints the modified string to the console, resulting in “Soul Power”.

JavaScript charAt() Method

JavaScript charAt() method returns the character at the specified index. String in JavaScript has zero-based indexing.

Example:This example describes the JavaScript string charAt() method.

JavaScript
let gfg = 'GeeksforGeeks';
let geeks = 'GfG is the best platform to learn and\n'+
'experience Computer Science.';

// Print the string as it is
console.log(gfg); 

console.log(geeks); 

// As string index starts from zero
// It will return first character of string
console.log(gfg.charAt(0)); 

console.log(geeks.charAt(5));

Output
GeeksforGeeks
GfG is the best platform to learn and
experience Computer Science.
G
s

Explanation:

The code initializes two strings gfg and geeks. It prints both strings to the console. Then, it uses the charAt() method to return the character at the specified index within each string. The first console.log() prints the first character of the string gfg (‘G’). The second console.log() prints the character at index 5 in the string geeks (‘i’).

JavaScript charCodeAt() Method

JavaScript charCodeAt() method returns a number that represents the Unicode value of the character at the specified index. This method accepts one argument.

Example: This example describes the JavaScript String charCodeAt() Method.

JavaScript
let gfg = 'GeeksforGeeks';
let geeks = 'GfG is the best platform\n\
to learn and experience\n\
Computer Science.';

// Return a number indicating Unicode
// value of character at index 0 ('G')
console.log(gfg.charCodeAt(0));
console.log(geeks.charCodeAt(5));

Output
71
115

Explanation:

The code initializes two strings gfg and geeks. It then uses the charCodeAt() method to return the Unicode value of the character at the specified index within each string. The first console.log() prints the Unicode value of the character at index 0 in the string gfg (‘G’). The second console.log() prints the Unicode value of the character at index 5 in the string geeks (‘o’).

JavaScript split() Method

JavaScript split() method splits the string into an array of sub-strings. This method returns an array. This method accepts a single parameter character on which you want to split the string.

Example: This example describes the JavaScript String split() method.

JavaScript
let gfg = 'GFG '
let geeks = 'stands-for-GeeksforGeeks'

// Split string on '-'. 
console.log(geeks.split('-'))

Output
[ 'stands', 'for', 'GeeksforGeeks' ]

Explanation:

The code initializes two strings gfg and geeks. It then uses the split() method to split the string geeks at each occurrence of the ‘-‘ character and returns an array containing the resulting substrings. Finally, it prints the array to the console.

More JS String Methods

Below is the JavaScript string functions list:

Instance Methods

Description

at()Find the character at the specified index.
anchor()Creates an anchor element that is used as a hypertext target.
charAt()Returns that character at the given index of the string.
charCodeAt()Returns a Unicode character set code unit of the character present at the index in the string.
codePointAt()Return a non-negative integer value i.e, the code point value of the specified element.
concat()Join two or more strings together in JavaScript.
endsWith()Whether the given string ends with the characters of the specified string or not.
includes()Returns true if the string contains the characters, otherwise, it returns false.
indexOf()Finds the index of the first occurrence of the argument string in the given string.
lastIndexOf()Finds the index of the last occurrence of the argument string in the given string.
localeCompare()Compare any two elements and returns a positive number
match()Search a string for a match against any regular expression.
matchAll()Return all the iterators matching the reference string against a regular expression.
normalize()Return a Unicode normalization form of a given input string.
padEnd()Pad a string with another string until it reaches the given length from rightend.
padStart()Pad a string with another string until it reaches the given length from leftend.
repeat()Build a new string containing a specified number of copies of the string.
replace()Replace a part of the given string with some another string or a regular expression
replaceAll()Returns a new string after replacing all the matches of a string with a specified string/regex.
search()Search for a match in between regular expressions and a given string object.
slice()Return a part or slice of the given input string.
split()Separate given string into substrings using a specified separator provided in the argument.
startsWith()Check whether the given string starts with the characters of the specified string or not.
substr()Returns the specified number of characters from the specified index from the given string.
substring()Return the part of the given string from the start index to the end index.
toLowerCase()Converts the entire string to lowercase.
toLocaleLowerCase()Returns the calling string value converted to a lowercase letter.
toLocaleUpperCase()Returns the calling string value converted to a uppercase letter.
toUpperCase()Converts the entire string to uppercase.
toString()Return the given string itself.
trim()Remove the white spaces from both ends of the given string.
trimEnd()Remove white space from the end of a string.
trimStart()Remove white space from the start of a string.
valueOf()Return the value of the given string.
string[Symbol.iterator]()This method is used to make String iterable. [@@iterator]() returns an iterator object which iterates over all code points of the String.
fromCharCode(n1, n2, …, nX)This method is used to create a string from the given sequence of UTF-16 code units. This method returns a string, not a string object.
fromCodePoint(a1, a2, a3, ….)This method in JavaScript that is used to return a string or an element for the given sequence of code point values (ASCII value).
isWellFormed()This method is used to check if the string contains a lone surrogate or not
String.raw(str, …sub)This is a static method that is used to get the raw string form of template literals. These strings do not process escape characters.
toWellFormed()This method is used to return where all lone surrogates of this string are replaced with the Unicode replacement character

Also Read

We have a complete list of Javascript string methods, to check those please go through this JavaScript String reference article.

Summary

JavaScript String is a collection of characters. They are one of the primitive data types. This tutorial covers these JavaScript string method that lets you manipulate strings.

JavaScript strings are a very important part of programming in JavaScript and one must know how to operate on them. Using these methods you will be able to perform numerous tasks involving strings.

Frequently Asked Questions – JavaScript String Methods

What are two string methods in JavaScript?

There are multiple string methods in JavaScript but here are the two common JS string methods are charAt(index) and indexof(substring).

What is the string method?

A string method in JavaScript is a built-in function that let’s you perform various operations like manipulate, search, extract or format strings.

How many methods does string have?

JS strings have over 30 methods. The exact number of methods depend on JavaScript engine and version of ECMAScript being used. New methods are also added after updates.

Why do JavaScript strings have string methods?

String methods in JavaScript help developers to easily operate on strings without having to manually code for basic string operations.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads