Skip to main content

String Methods for Regular Expressions (Live Playground)

In this tutorial, we'll explore some of the helpful string methods in JavaScript that work with regular expressions. These methods allow us to perform various operations on strings, such as searching, matching, and replacing.

The search() method returns the index of the first match found in the string. If there's no match, it returns -1.

Example:

const regex = /world/i;
const str = 'Hello, world!';

console.log(str.search(regex)); // 7
Live Playground, Try it Yourself

match()

The match() method retrieves all matches of a regular expression in a string. It returns an array of matched strings, or null if there are no matches.

Example:

const regex = /\w+/g; // one or more word characters
const str = 'Hello, world!';

console.log(str.match(regex)); // ["Hello", "world"]
Live Playground, Try it Yourself

replace()

The replace() method allows you to search and replace a substring that matches the regular expression.

Example:

const regex = /world/i;
const str = 'Hello, world!';
const replacement = 'there';

console.log(str.replace(regex, replacement)); // "Hello, there!"
Live Playground, Try it Yourself

split()

The split() method splits a string into an array of substrings using a regular expression as the separator.

Example:

const regex = /[\s,]+/; // one or more whitespace characters or commas
const str = 'Hello, world! How are you?';

const words = str.split(regex);

console.log(words); // ["Hello", "world!", "How", "are", "you?"]
Live Playground, Try it Yourself

Conclusion

In this tutorial, we covered some essential string methods in JavaScript that work with regular expressions, such as search(), match(), replace(), and split(). These methods make it easier to perform various operations on strings, like searching, matching, and manipulating text. As you continue to work with regular expressions, you'll discover their power and versatility in solving a wide range of programming tasks.