I’m making some code that will extract all links from a block of text. I have a regex pattern, I’m just wondering if there is a way to get all matches of that regex pattern?
I’ve tried some code I found but that returned nothing every time.
Any answers are appreciated.
let string = "Hello world"
let m, newtext, re = /o/g
do {
m = re.exec(string);
if (m) {
newtext = (m[1], m[2]);
}
} while (m);
console.log(m,newtext)
This is not a duplicate as the post did not solve my problem.
And I’ve also used this code, but I’m getting an error: "findAll is not a function or its return value is not iterable"
function link() {
const findAll = (value, expr) => {
const iterator = value.matchAll(typeof expr === 'string' ?
new RegExp(expr, 'gd') :
new RegExp(expr.source, [...new Set((expr.flags + 'gd').split(''))].join('')));
let _next;
[_next, iterator.next] = [iterator.next, function(){
const result = _next.call(iterator);
if(!result.done){
const {0: text, indices: [[startIndex, endIndex]]} = result.value;
console.log(
'done:', false,
'value:', {text, startIndex, endIndex}
);
}
console.log (result);
}];
console.log(iterator);
}
console.log('matching with string:');
for (const m of findAll(str, re)) {
console.log(JSON.stringify(m));
}
console.log('matching with regex:');
for (const m of findAll(str, re)) {
console.log(JSON.stringify(m));
}
}
3
Answers
As @Konrad mentioned. One of the best ways is to use
matchAll
. Example:Here is a modified version of Jivopis’ response.
I created a function called
findAll
that takes a string and a pattern (string or regex) and return a list of objects. These objects contain thetext
,startIndex
, andendIndex
for each matched substring in the origin text.Output
Jumping into the wagon, here is a modified version of Mr. Polywhirl’s response:
.matchAll
so we could use the iterator with all of its benefits, for example we can break the loop thus skipping the rest and optimizing performance.next()
of the iterator to get data in our needed format.d
flag to the regular expression so we can get start and end match indices automaticallygd
flags