14 JavaScript String Methods & How to Use Them

Download Now: Introduction to JavaScript Guide
Athena Ozanich
Athena Ozanich

Published:

JavaScript is a simple and powerful programming language that creates software and technology for many applications. From web development to programming interfaces and software for NASA, it has grown in popularity since its inception. The language is so robust that there are many topics to learn and many ways to use them.

You woman studying JavaScript string methods and how to use them in her software development.

This post will cover JavaScript string methods that modify and manipulate string values. We'll review built-in string methods and others that can perform various tasks on strings. Furthermore, you will see some examples of syntax you can use in CodePen to help solidify your understanding.

Without further delay, let's jump right in.

Download Now: An Introduction to JavaScript  [Free Guide]

Table of Contents

JavaScript Strings Explained

The JavaScript string is a data type used to convey information as text, which differs from numerical data types like int. Specifically, an int value can only be a number, but strings can contain any character. Because of this, they are commonly used in software development across different industries and languages.

Because of the popularity and need for string data, JavaScript offers many different methods for interacting with and modifying strings. In fact, there are over 30 distinct methods for modifying and manipulating string values.

What are JavaScript string methods?

The usefulness of strings is boundless, so it's crucial to understand how you can use them to your advantage. Arguably, the most common task you will complete is modifying a string in some way. To facilitate that process, JavaScript includes a string object allowing methods and properties to be executed on string values.

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.

Built-in JavaScript String Methods

In many languages, strings are objects and thus have several properties and methods to build on their functionality. In JavaScript, however, strings are a primitive data type and thus do not have any built-in methods or properties. Despite this fact, JavaScript does support several methods and a couple of properties on strings.

Because JavaScript treats strings as objects when methods or properties are executed, they still have the ability to be built up. This ability is due to the string object in the JavaScript library or framework, though it’s not intended for creating string objects. Creating string objects results in slower processing and potentially errant results, so use them cautiously.

Now that you've learned the theory behind methods and strings, let's dive into how they work together.

How to Use String Methods in JavaScript

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”; str.someRandomMethod();

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?”; str.trim(); /*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.”; str.replace(/\s/g,'');\ /*Would return the string “I’maTimelordfromtheplanetGallifrey.”*/

The above code uses a regular expression that equates to “all-white space, inclusive”, which tells JavaScript to remove all occurrences of any white space.

Now that we've reviewed what string methods are and how to use them let's look at a comprehensive list of string methods available in JavaScript.

JavaScript String Methods & Examples

This section will review some of the more popular JavaScript string methods. We've also included this cheatsheet below that you can keep as a handy reference.

cheatsheat for javascript string methods

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

str.toLowerCase(); /*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

str.toUpperCase(); /*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; num.toString(); /*Would return “904”*/

4. Substring Method: substring()

The substring method extracts characters from a string between two specified indices.

Substring Method Example

str.substring(31, 40); /*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

str.includes("Timelord"); /*Would return boolean true*/

6. Match Method: match()

The match method returns a string object with a matching value.

Match Method Example

str.match("Timelord"); /*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(); console.log(newMessage); /*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); console.log(answer); /*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"); console.log(result); /*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"); console.log(result); /*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); console.log(sayHello); /*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!"; console.log(text.search("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!"); console.log(specialCharacters); /*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.

New Call-to-action

Topics: Javascript

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about one of the world's most popular programming languages.

CMS Hub is flexible for marketers, powerful for developers, and gives customers a personalized, secure experience

START FREE OR GET A DEMO