JavaScript Tip: Iterating Through Regular Expression Matches

preview_player
Показать описание
Many developers know how to use regular expressions in JavaScript, but few know the ins and outs of the exec method, a method of the regular expression object. It has some nice features one of which is making it possible to iterate over matches.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

The next function is good in certain situation - while making it an array, is most of time more useful.. So wthen it can be looped through...

magnusfohlstrom
Автор

Here is an function that will reveal the word that contains the matched letter, from the string..
let str = 'How many Os are in our overly long string';
function word(str, index, rgx){
let b = i = Array.from(str.matchAll(rgx))[index]?.index,
w = [str[b]], s = ' ';
if(i === undefined) return false;
while (i <= str.length && ![w.at(0), w.at(-1)].every(e => e === s)){
w.at(0) !== s && w.unshift(str[--b]);
w.at(-1) !== s && w.push(str[++i]);
}
return w.join('').trim();
}
Index 2 of the matchAll will return....
word(str, 2, /o/g); --> 'overly'

magnusfohlstrom
Автор

Here is an example, to list all words of search matches comes from..
function allWords(str, rgx){
return Array.from(str.matchAll(rgx)).reduce((a, c) => {
let b = f = c.index,
w = [str[b]], s = ' ';
while (b > -1 && f <= str.length && ![w.at(0), w.at(-1)].every(e => e === s)){
w.at(0) !== s && w.unshift(str[--b]);
w.at(-1) !== s && w.push(str[++f]);
}
a.push(w.join('').trim());
return a;
}, []);
}
allWords(str, /o/g) --> (4) ['How', 'our', 'overly', 'long']

magnusfohlstrom
Автор

What happened to you? So long my friend. Have a great one Steven.

polliluiz