To find find all the matches of a regular expression in this string in JavaScript, call match() method on this string, and pass the regular expression as argument. match() method returns an array of strings containing all the matches found for the given regular expression, in this string.
Using RedExp Loop you can find all entries of a phrase you seek in a text and process them in a loop. A phrase mask is specified by a regular expression. The search result of every iteration is saved in a variable as a standard comma-separated string.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.
var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
doSomethingWith(result);
}
Three approaches depending on what you want to do with it:
Loop through each match: .match
targetText.match(/e(.*?)e/g).forEach((element) => {
// Do something with each element
});
Loop through and replace each match on the fly: .replace
const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => {
// Return the replacement leveraging the parameters.
});
Loop through and do something on the fly: .exec
const regex = /e(.*?)e/g; // Must be declared outside the while expression,
// and must include the global "g" flag.
let result;
while(result = regex.exec(targetText)) {
// Do something with result[0].
}
Try using match() on the string instead of exec(), though you could loop with exec as well. Match should give you the all the matches at one go. I think you can omit the global specifier as well.
reg = new RegExp(/e(.*?)e/);
var matches = targetText.match(reg);
targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"
reg = new RegExp(/e(.*?)e/g);
var result;
while (result = reg.exec(targetText))
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With