JavaScript coders frequently face problems that call for string manipulation. When retrieving an email, for instance, you may need to lowercase all the characters or use a regular expression to determine if the supplied password meets all requirements.

All of these string manipulations, and more, can be accomplished quickly and easily with the help of JavaScript's string methods. Listed below are ten string methods, along with examples to help you learn them.

JavaScript string methods: what exactly are they?

In computing, strings, which store information as a string of characters, play a fundamental role. This data structure is in the standard libraries of Python, JavaScript, Java, and a lot of other languages.

JavaScript has a number of built-in methods, known as "string methods," that developers can use to perform common string-based tasks without having to write their own code. They are executed via dot notation with the string variable as their target.

String.concat()

The concat() function is used to combine several strings into one. By providing multiple arguments, this method can be used to merge several strings into a single one. There were no alterations made to the primary string.

// Sample #1
let copy1 = "cat";
let copy2 = "dog";
let result = copy1.concat(copy2);


// Sample #2
let copy1 = "New";
let copy2 = "York!";
let result = copy1.concat(" ", copy2);

//NOTES
//	The concat() method joins two or more strings.
//	The concat() method does not change the existing strings.
//	The concat() method returns a new string.

String.indexOf() and String.lastIndexOf()

The indexOf() function can be used to find the starting index of a string that contains a given character or substring. It begins on the left and works its way through the string, looking for the specified pattern.

// Sample #1
let copy = "Hey, welcome to betteratcoding";
let result = copy.indexOf("welcome");


// Sample #2
let copy = "Hey, welcome to betteratcoding";
let result = copy.indexOf("Welcome");


// Sample #3
let copy = "Hey, welcome to betteratcoding";
copy.indexOf("a");

//NOTES
//	The indexOf() method returns the position of the first occurrence of a value in a string.
//	The indexOf() method returns -1 if the value is not found.
//	The indexOf() method is case sensitive.

String.charAt()

The charAt() string method finds and returns a character within a string. It takes a single argument, the index of the character, and returns that character. The index can have values ranging from 0 to length minus 1.

//Sample #1 (Get the first character in a string)
let copy = "WELCOME TO BETTER AT CODING";
let letter = copy.charAt(0);

//Sample #2 (Get the second character in a string)
let copy = "HOLA MUNDO";
let letter = copy.charAt(1);

//Sample #3 (Get the last character in a string)
let copy = "HOLA MUNDO";
let letter = copy.charAt(text.length-1);

//NOTES
//The charAt() method returns the character at a specified index (position) in a string.
//The index of the first character is 0, the second 1, ...

String.replace()

The replace() method enables you to perform this type of substitution within a string. The first argument specifies the substring to be replaced, and the second specifies the substring to be used in its place; both arguments are required for this method to function. This method preserves the original string.

//Sample #1  (Replace Microsoft)
let copy = "Visit Miami!";
let result = text.replace("Miami", "St.Pete");


//Sample #2 (A global replacement)
let copy = "Dr.James has a blue house and a blue car";
let result = copy.replace(/blue/g, "red");

//NOTES
//	The replace() method searches a string for a value or a regular expression.
//	The replace() method returns a new string with the value(s) replaced.
//	The replace() method does not change the original string.

String.split()

The split() method's separator argument separates words or characters. This method returns an array. This array contains every character or substring, divided by the delimiter. It does not alter the string.

//Sample 1 (Split the words)
let copy = "How are you doing today?";
const myArray = copy.split(" ");

//Sample 2 (Split the words, and return the second word)
let copy = "How are you doing today?";
const myArray = copy.split(" ");
let word = myArray[1];

//Sample 3 (Use the limit parameter)
const myArray = copy.split(" ", 3);

//Sample 4 (Split the characters, including spaces)
const myArray = copy.split("");

String.toLowerCase() and String.toUppperCase()

To convert a string from upper to lower case, use String.toLowerCase() or String.toUpperCase().
Each character in a string can be converted to lowercase or uppercase using the string methods toLowerCase() and toUpperCase(), respectively. These functions safeguard the integrity of a string.

//Sample 1 (Convert to lowercase)
let copy = "I am Hungry!";
let result = copy.toLowerCase();

//Sample 2 (Convert to uppercase)
let copy = "I am Hungry!";
let result = copy.toUpperCase();

//NOTES
//	The toLowerCase() method converts a string to lowercase letters.
//	The toLowerCase() method does not change the original string.

String.substring()

The substring() method can be used to extract a specific segment of a string. This procedure must be executed with the beginning and ending indexes. The start index specified causes the printing of a substring to begin at that position and continue until the end index is reached (minus 1).

//Sample #1 (Extract a substring from text)
let copy = "Hello world!";
let result = copy.substring(1, 4);

//Sample #2 (Start from position 2)
let result = copy.substring(2);

//NOTES
//	The substring() method extracts characters, between two indices (positions), from a string, and returns the substring.
//	The substring() method extracts characters from start to end (exclusive).
//	The substring() method does not change the original string.
//	If start is greater than end, arguments are swapped: (4, 1) = (1, 4).
//	Start or end values less than 0, are treated as 0.

String.search()

The search() method can be used to find a particular character or substring within a larger string. This function takes an arbitrary character sequence or substring as an argument and iteratively follows it through the supplied string. If there is a match, the beginning index of the shared text is returned. When this method fails, it returns -1.

//Sample #1 (Extract a substring from text)
let text = "Hello world!";
let result = text.substring(1, 4);

//Sample #2 (Start from position 2)
let result = text.substring(2);


//NOTES
//	The substring() method extracts characters, between two indices (positions), from a string, and returns the substring.
//	The substring() method extracts characters from start to end (exclusive).
//	The substring() method does not change the original string.
//	If start is greater than end, arguments are swapped: (4, 1) = (1, 4).
//	Start or end values less than 0, are treated as 0.

String.trim()

Trim() removes blank spaces at the start and end of a string. This method does not alter the original string and requires no parameters. It comes in handy when checking the accuracy of user-submitted form submissions.

//Sample #1 (Extract a substring from text)
let text = "Hello world!";
let result = text.substring(1, 4);

//Sample #2 (Start from position 2)
let result = text.substring(2);


//NOTES
//	The substring() method extracts characters, between two indices (positions), from a string, and returns the substring.
//	The substring() method extracts characters from start to end (exclusive).
//	The substring() method does not change the original string.
//	If start is greater than end, arguments are swapped: (4, 1) = (1, 4).
//	Start or end values less than 0, are treated as 0.

String.slice()

The slice() method is used to extract a section of a string and return it as a new string. The method accepts two arguments: the slice's starting index (inclusive) and ending index (exclusive).

// Sample #1 (Slice the first 5 positions)
let text = "Hello world!";
let result = text.slice(0, 5);

// sample #1 (From position 3 to the end)
 let result = text.slice(3);


// NOTES
//	The slice() method extracts a part of a string.
//	The slice() method returns the extracted part in a new string.
//	The slice() method does not change the original string.
//	The start and end parameters specifies the part of the string to extract.
//	The first position is 0, the second is 1, ...
//	A negative number selects from the end of the string.

Summary

In conclusion, the string methods available in JavaScript make it easy and powerful to work with strings. With these methods, developers can quickly and easily search, replace, and format strings without having to write long, complicated code. Also, most modern browsers support JavaScript string methods, making them a solid and cross-browser choice for building websites. Using these techniques can make code more efficient and easier to read, which makes it easier to fix and update in the future. String methods in JavaScript are useful in so many situations that they should be part of every web developer's toolbox.

Many thanks to the hardworking authors and developers behind sites like w3schools.com, developer.mozilla.org, and javascript.info for always providing reliable information.

Tagged in:

Javascript

Last Update: January 26, 2023