To match a substring inside a string using regular expressions (regex) in JavaScript, you can use the match()
method. Let’s explore some ways :
Simple regex
let str = "Hello codeymaze!";
let regex = /codeymaze/;
let match = str.match(regex);
if (match) {
console.log("Match found:", match[0]);
} else {
console.log("No match found.");
}
In this example, the regular expression /codeymaze/
is used to search for the substring “codeymaze” within the str
variable. The match()
method returns an array with the matched substring, or null
if no match is found.
Using test()
you can use the test()
method to check if a substring exists in the string.
let str = "Hello codeymaze!";
let regex = /codeymaze/;
if (regex.test(str)) {
console.log("Substring found");
} else {
console.log("Substring not found");
}
The test() method used to check if the regex pattern matches any part of the string. It will return true if the regex pattern is found in the string, otherwise returns false.
Complex regex
let str = "Hello codeymaze.";
let regex = /\bco\w*/;
let match = str.match(regex);
if (match) {
console.log("Match found:", match[0]);
} else {
console.log("No match found.");
}
In this example, the regular expression /\bco\w*/
is used to match a word that starts with “co” and can have any number of additional word characters (like “codeymaze”).
The \b
in the regex pattern represents a word boundary, which ensures that the match is a complete word and not just a substring within a larger word.
Using exec()
let str = "The rain in Italy stays mainly in the plain.";
let regex = /\bit\w*/;
let match = regex.exec(str);
if (match) {
console.log("Match found:", match[0]);
} else {
console.log("No match found.");
}
The exec()
method returns an array with the matched substring as the first element, or null
if no match is found.