Javascript equivalent to Python's re.findall()
The equivalent to this Python code which is using re.findall()
import re
hashtag_regex = r"(\B#\w\w+)"
hits = re.findall(hashtag_regex, "This is a string #with #hashtags")
print(hits) # prints ['#with', '#hashtags']
in Javascript is
const string = "This is a string #with #hashtags";
const re = /(\B#\w\w+)/g;
const hits = [];
// Iterate hits
let match = null;
do {
match = re.exec(string);
if(match) {
hits.push(match[0]);
}
} while (match);
console.log(hits); // Prints [ '#with', '#hashtags' ]
You need to assign your regular expression to a variable like re
! If you use
match = /(\B#\w\w+)/g.exec(string); // WRONG ! Don't do this !
you will create an infinite loop which always generates the first hit in the string, if any!