JavaScript - How to Match Multiple Parts of a String Using RegExp?
Last Updated :
06 Dec, 2024
In JavaScript, the regular expression (RegExp) object provides a powerful mechanism to search, match, and manipulate strings. One of the common use cases is matching multiple parts of a string that satisfy a certain pattern. You can easily do this using global (g) and other RegExp features.
1. Using Global (g) Flag to Match Multiple Occurrences
The g flag enables global matching, which allows the regular expression to match all occurrences of a pattern in the string, not just the first one.
JavaScript
let s = "apple orange apple banana apple";
let regex = /apple/g;
let res = s.match(regex);
console.log(res);
Output[ 'apple', 'apple', 'apple' ]
- /apple/g matches the word "apple" globally.
- The match() method returns an array of all matched parts of the string.
2. Using match() with Capture Groups
You can use parentheses () to define capture groups in a regular expression. This allows you to match and extract multiple parts of the string that satisfy different conditions.
JavaScript
let s = "apple123 orange456 apple789";
let regex = /(\w+)(\d+)/g;
let res = [...s.matchAll(regex)];
console.log(res);
Output[
[
'apple123',
'apple12',
'3',
index: 0,
input: 'apple123 orange456 apple789',
groups: undefined
],
[
'orange456',
'orange45',
'6',
index: 9,
input: ...
- (\w+) matches the word characters (letters) and (\d+) matches digits.
- matchAll() returns all matches as an array of arrays, where each sub-array contains the full match and the captured groups.
3. Using exec() with Global Flag
The exec() method allows you to find multiple matches one at a time. It returns an array for each match, and with the global flag, it can be used in a loop to find all matches.
JavaScript
let s = "apple123 orange456 apple789";
let regex = /(\w+)(\d+)/g;
let ress;
while ((res = regex.exec(s)) !== null) {
console.log(res);
}
Output[
'apple123',
'apple12',
'3',
index: 0,
input: 'apple123 orange456 apple789',
groups: undefined
]
[
'orange456',
'orange45',
'6',
index: 9,
input: 'apple123 orange456 apple789',
...
- regex.exec(s) finds one match at a time, and with each iteration, it returns the full match and the captured groups.
- The while loop continues until all matches are found.
4. Using split() to Split String by Multiple Parts
The split() method can be used with a regular expression to break a string into multiple parts. If the regular expression matches multiple segments, the split() method will break the string accordingly.
JavaScript
let s = "apple123 orange456 apple789";
let regex = /\d+/g;
let res = s.split(regex);
console.log(res);
Output[ 'apple', ' orange', ' apple', '' ]
- /\d+/g matches sequences of digits.
- split() breaks the string wherever a match is found, returning an array of non-matching parts.
5. Using Non-Capturing Groups to Match Multiple Patterns
Non-capturing groups (?:...) allow you to combine multiple patterns without creating separate capturing groups. This is useful when you need to match multiple patterns in a string but don’t need to extract the individual parts.
JavaScript
let s = "apple123 orange456 apple789";
let regex = /(?:apple|orange)\d+/g;
let res = s.match(regex);
console.log(res);
Output[ 'apple123', 'orange456', 'apple789' ]
- (?:apple|orange) matches either "apple" or "orange".
- \d+ matches one or more digits after "apple" or "orange".
- The g flag ensures all matching parts are found in the string.
6. Matching Multiple Patterns with OR (|) Operator
The | (OR) operator in regular expressions allows you to match one pattern or another. This can be used to match multiple parts of a string that satisfy different conditions.
JavaScript
let s = "apple orange123 banana456";
let regex = /apple|orange\d+/g;
let res = s.match(regex);
console.log(res);
Output[ 'apple', 'orange123' ]
- /apple|orange\d+/g matches either "apple" or "orange" followed by one or more digits.
- The g flag ensures that all matches are found in the string.
Similar Reads
How to Search for Multiple Words Within a String or Array in JavaScript?
To search for multiple words within a string or an array in JavaScript, you can use different approaches depending on the data structure. Hereâs how to perform the search effectively:1. Searching for Multiple Words in a StringTo check if a string contains multiple words, you can use String.prototype
3 min read
JavaScript RegExp multiline Property
The multiline property of a JavaScript regular expression indicates whether the m (multiline) flag is enabled. When enabled, the ^ and $ anchors match the start and end of each line within a string, rather than the entire string.JavaScript// Regular expression without 'm' flag let regex1 = /^test$/;
2 min read
How to Search a String for a Pattern in JavaScript ?
Here are two ways to search a string for a pattern in JavaScript.1. Using string search() MethodThe JavaScript string search() method is used to serch a specified substing from the given string and regular expression. It returns the index of the first occurrence of the pattern or -1 if the pattern i
2 min read
JavaScript RegExp toString() Method
The RegExp.toString() method in JavaScript is used to return the string representation of a regular expression object. It converts the regular expression to a string, including its pattern and flags. JavaScriptlet reg1 = /hello/i; let reg2 = /\d{3}-\d{2}-\d{4}/; console.log(reg1.toString()); console
2 min read
JavaScript String match() Method
The match() method in JavaScript is used for identifying and retrieving substrings that fit a specified pattern, defined by a regular expression. It is often used when you need to find particular patterns within strings, enabling efficient text processing. This method returns an array of matched sub
3 min read
Replace all Occurrences of a Substring in a String in JavaScript
Given a String, the task is to replace all occurrences of a substring using JavaScript. The basic method to replace all substring of a string is by using string.replaceAll() method.The string.replaceAll() method is used to search and replace all the matching substrings with a new string. We can use
2 min read
JavaScript String substring() Method
The substring() method in JavaScript is used to extract characters between two indices from a string, without modifying the original string. This method returns a new string that is a part of the original string, starting from a specified position up to (but not including) another specified position
5 min read
How to return all matching strings against a regular expression in JavaScript ?
In this article, we will learn how to identify if a string matches with a regular expression and subsequently return all the matching strings in JavaScript. We can use the JavaScript string.search() method to search for a match between a regular expression in a given string. Syntax: let index = stri
3 min read
Javascript String matchAll() Method
The JavaScript matchAll method is very useful for working with regular expressions. It allows developers to find all matches of a pattern in a string, returning an iterator with detailed match results. This method is especially useful for extracting multiple pieces of information from text efficient
4 min read
JavaScript - How to Use RegExp in Switch Case Statements?
To make your JavaScript switch statements more dynamic and flexible, you can use regular expressions (RegExp). Here are the various ways to use RegExp in switch case statement.1. Using test() Method in switchThe test() method can be used to check if a string matches a given regular expression. Letâs
3 min read