Without further delay, let's jump right in.
Table of Contents
- How to Use String Methods
Check out this video on string methods to learn more about what they are.
One use of strings is sterilizing any malicious code from being injected into a program or software. This process happens using a regex — or regular expression — which in no way looks like regular expressions. Regular expressions are patterns on strings to ensure they meet specific formatting requirements.
Now that you've learned the theory behind methods and strings, let's dive into how they work together.
Truthfully, using string methods is relatively easy to do. However, understanding what's happening is a different topic. Let’s clarify this with an example. After all, using a string method is simply a matter of understanding the syntax.
With that in mind, let’s look at a code example of the syntax below.
let str = “Doctor Who”;
That is the bare bones of every string method. It starts with a variable holding a primitive string value. You can then chain the desired method to the string variable using the dot notation and finish it off with parenthesis and a semicolon. Here is a code snippet showing how to use the trim() method.
let str = “Yes, but Doctor Who?”;
/*Would return the string “Yes,butDoctorWho?”*/
Simple enough, right? Well, what if that method requires a parameter? In that case, the method will accept some criteria on what to do with the string value. This behavior changes things a little.
Let's look at a simple example of a method with parameters. The code below does the same as the code above, removing any whitespace from a string. Only this time, it's done using the replace() method.
The replace method accepts two parameters, the first is what the string method should look for, and the second is the value to replace with the target.
let str = “I’m a Timelord from the planet Gallifrey.”;
/*Would return the string “I’maTimelordfromtheplanetGallifrey.”*/
For these examples, let's use the following string:
let str = “I’m a Timelord from the planet Gallifrey.”;
Copy and paste these values into the CodePen below to test them out for yourself.
1. Lowercase Method: toLowerCase()
The lowercase method returns a string with all values converted to lowercase letters.
Lowercase Method Example
/*Would return the string, "i’m a timelord from the planet gallifrey."*/
2. Uppercase Method: toUpperCase()
The uppercase method returns a string with all values converted to uppercase.
Uppercase Method Example
/*Would return the string, "I’M A TIMELORD FROM THE PLANET GALLIFREY."*/
3. String Method: toString()
The string method returns a string or string object as a string.
String Method Example
let num = 904;
/*Would return “904”*/
4. Substring Method: substring()
The substring method extracts characters from a string between two specified indices.
Substring Method Example
/*Would return the string “Gallifrey”. NOTE: Excluding the second index will return all characters after the start index.*/
5. Includes Method: includes()
The includes method returns a string if it contains a specified value.
Includes Method Example
/*Would return boolean true*/
6. Match Method: match()
The match method returns a string object with a matching value.
Match Method Example
/*Would return an array object with the matched value. Regular expressions can also be used.*/
7. Concat Method: concat()
The contact method returns two or more joined strings.
Concat Method Example
str.concat(” I’m The Doctor, look me up!”);
/*Would return “I’m a Timelord from the planet Gallifrey. I’m The Doctor, look me up!”*/
8. Trim Method: trim()
The trim method removes unneeded whitespace from the start and end of a string.
Trim Method Example
const str = " Welcome to HubSpot ";
const newMessage = str.trim();
/*Would return Welcome to HubSpot*/
9. Eval Method: eval()
The eval method allows code written as a string to be evaluated and executed.
Eval Method Example
let expression = "2 + 3";
let answer = eval(expression);
/*Would return 5*/
10. Replace Method: replace()
The string replace method returns a new string to replace a piece of an existing string.
Replace Method Example
let text = "Hello HubSpot!";
let result = text.replace('HubSpot', 'Reader');
/*In this example, the replace method searches for ‘HubSpot’ and replaces it with ‘Reader’. The resulting string is “Hello Reader!”. */
11. Test Method: test()
The test method checks if there is a match in a string. It returns the value, True or False, depending on the outcome.
Test Method Example
let text = "Hello Reader";
let result = text.test("o");
/*In this example, the test method returns true because there is an 'o' in our string. */
12. Repeat Method: repeat()
The repeat() method is used to repeat a given string a specified number of times.
Repeat Method Example
let sayHello = 'Hello HubSpotter!'.repeat(3);
/*In this example, the repeat() method repeats a given string (‘Hello HubSpotter!’) three times. The output is then printed out on the console. */
13. Search Method: search()
The search() method is used to search for a pattern in a string and returns the index position of the match.
Search Method Example
let text = 'Hello HubSpotter!';
/*In this example, the search() method is used to search for the string ‘HubSpotter’ in the string ‘Hello HubSpotter!’. The output is then printed out on the console, which is 6 – indicating that the pattern matches at index position 6. */
14. Escape Method: escape()
The escape method returns a string that’s encoded so it can be transmitted to different computers on different networks.
Note: This function has been deprecated and is not recommended for use. Instead, you can use the encodeURI() function.
Escape Method Example
let specialCharacters = escape("I'm John Smith!");
/*In this example, the escape() method is used to encode special characters in a string ("I'm John Smith!"). The output is then printed out on the console. */
Getting Started Using JavScript String Methods
This list is not exhaustive; there are many more methods, and some are much less known than others. An example of these lesser-known methods would be the padStart() and padEnd() methods which allow you to add a string to the beginning and end of a string value.
There is a lot to learn under the umbrella of strings and string methods. The best way to solidify all the information is to practice using them. Endless applications use strings, and even more ways methods can help.
Working with string methods, you can learn to understand the boundaries and behaviors and how to use methods together. Combining string methods allows you to perform powerful tasks and do almost anything your software may require.