While programming in JavaScript, you’ll often come across scenarios that require string manipulation. For instance, while retrieving an email, you might need to convert all the characters to lowercase or use a regular expression to check whether the entered password satisfies all the conditions.
JavaScript string methods will help you perform all these operations on a string as per your requirements with ease. Here are 10 string methods with examples to help you get a good grasp on them.
What Are JavaScript String Methods?
Strings are a fundamental data structure that consists of a sequence of characters. This data structure is a part of all major programming languages, including Python, JavaScript, Java, and more.
String methods are the pre-built JavaScript methods that help developers perform common operations on strings without needing to write the code manually. They’re run using dot-notation attached to the string variable.
Since they’re just JavaScript functions, they always end with parenthesis which can hold optional arguments. It’s essential to know what JavaScript is and how it works before proceeding further. Let’s get started and learn these methods in greater detail.
For the upcoming methods, let’s take a string variable str with the value of “Welcome to MUO!” as an example.
let str = "Welcome to MUO!"
1. String.toLowerCase() and String.toUppperCase()
The toLowerCase() string method converts all the characters of the given string to the lowercase format, and similarly, the toUpperCase() method converts all the characters to the uppercase format. These functions don’t modify the original string.
Syntax:
toUpperCase()
toLowerCase()
Let’s check out these two methods with a quick example:
console.log(str.toLowerCase());
console.log(str.toUpperCase());
console.log(str);
On running the above code on the console, you will receive the following output:
"welcome to muo!"
"WELCOME TO MUO!"
"Welcome to MUO!"
2. String.concat()
The concat() method is used to join two or more strings together. You can add one or more arguments to this method to concatenate them into a single string. It does not make any modification to the original string.
Syntax:
concat(str1, str2, str3, ...)
Here’s an example that showcases the concatenation of two strings to form a new string:
let str2 = " How are you?";
let newString = str.concat(str2);
console.log(newString);
"Welcome to MUO! How are you?"
3. String.indexOf() and String.lastIndexOf()
The indexOf() method helps you to find out the first index at which the specified character or substring is present. It begins from the left-hand side and traces the string to check if the given argument matches.
Syntax:
indexOf(str)
Let’s find out the index at which MUO is present in the string with an example:
console.log(str.indexOf('MUO'));
11
If the given argument is not present in the string, the method returns a value of -1.
console.log(str.indexOf('Hello'));
-1
Similarly, the lastIndexOf() method returns the index of the last occurrence of the given character or string. Here’s an example:
console.log(str.lastIndexOf('e'));
6
Even though the alphabet e appears at index 1, the last occurrence of this character is at index 6 and hence is returned as the output.
4. String.charAt()
The charAt() string method returns the character at the specified index in the string. It accepts only one argument, the index at which the character is to be retrieved. The index value ranges from 0 to length – 1.
Syntax:
charAt(index)
Here’s an example of the charAt() method:
console.log(str.charAt(9));
console.log(str.charAt(0));
console.log(str.charAt(str.length - 1));
o
W
!
In the above example, when str.length – 1 was passed as the argument, the method returns the last character of the string. If you enter an invalid index that is beyond the permissible range, this method returns -1.
5. String.charCodeAt()
Similar to the charAt method, the charCodeAt() method returns the ASCII value of the character at the specified index. This string method takes only one argument, the index from which the character is to be retrieved.
Syntax:
charCodeAt(index)
str.charCodeAt(5);
str.charCodeAt(str.length - 1);
109
33
Once again, the index value ranges from 0 to length – 1 and if you try to pass an index beyond the permissible limit, this method will return -1.
6. String.replace()
As the name suggests, the replace() method helps you substitute one part of the string with another part. This method takes two arguments: the first one is the substring to be replaced, and the second one is the substring to be replaced with. This method does not make any modification to the original string.
Syntax:
replace(str1, str2)
For example, if you want to replace the word MUO with this website in the string variable, you can use the replace() method like this:
let newString = str.replace("MUO", "this website");
console.log(newString);
console.log(str);
Welcome to this website!
Welcome to MUO!
7. String.split()
The split() method is used to break down all the words or characters in a string as per the separator argument passed to the method. The return type of this method is an array. This array consists of all the characters or substrings, split according to the given separator. This method does not modify the original string.
Syntax:
split(separator)
For example, if a blank space (” “) is passed as the separator argument to the split method, this is how the output will look:
let splitArray = str.split(" ");
console.log(splitArray);
['Welcome', 'to', 'MUO!']
If you don’t pass an argument to the split() method, it’ll return an array with a single element consisting of your string variable’s value.
let splitArray = str.split();
console.log(splitArray);
['Welcome to MUO!']
8. String.substring()
The substring() method is used to obtain a substring or part of the original string. This method takes two parameters: the start index and the end index. The output substring starts from the specified start index and prints up to the end index – 1.
Syntax:
substring(startIndex, endIndex)
Here’s a quick example of the substring() method:
console.log(str.substring(2,8));
"lcome"
Note that the character at the end index is not a part of the output.
9. String.search()
The search() method helps to find a particular substring or character inside the original string. This method accepts a group of characters or substring as an argument and traces through the string. Upon finding a match, the starting index of the matched portion is returned. Otherwise, this method returns -1.
Syntax:
search(substring)
You can make use of the search() method in this manner:
console.log(str.search("MUO"));
console.log(str.search("2"));
11
-1
10. String.trim()
The trim() method removes all the white spaces in the string, before the first character and after the last character. This method does not require you to pass any parameters and doesn’t modify the original string. It’s extremely helpful for user input validation in forms.
Syntax:
trim()
Let’s take a new example to explore this string method:
let untrimmedString = " Welcome to MUO! ";
let trimmedString = untrimmedString.trim();
console.log(trimmedString);
console.log(untrimmedString);
"Welcome to MUO!"
" Welcome to MUO! "
More JavaScript Methods to Check Out
So this was a quick roundup of some common string methods that can help you be more productive as a JavaScript developer. These methods will also help you ace your coding interviews for string-related questions. Practice makes perfect, so go ahead and try these methods out in your own console.
Once you’re thorough with string methods, it might be worthwhile to take a look at some array methods that can further enhance your mastery of JavaScript.