I have a simple script to match series episode codes, like S01E02 or s09e11. The idea is to find all of the episode codes in the provided text and create an array of objects, containing all episodes found.
I first use match()
to get the array of all matched codes, then I loop through the codes to extract the season and episode number.
Problem is, when I use the same regex patter with /gi
modifiers both for finding all matches, and extracting the episode details, I get an error: Uncaught TypeError: Cannot read property '1' of null
(see the Console output).
Case 1 (failing) -- fiddle 1
var episodePatternGI = /s(\d{1,2})e(\d{1,2})/gi;
var matches = 'S3E1 hehehe bla s09e12'.match(episodePatternGI);
var episodes = [];
matches.forEach(function(val) {
var ep = episodePatternGI.exec(val);
episodes.push({
s: ep[1],
e: ep[2]
});
});
console.log(episodes);
Case 2 (working) -- fiddle 2
var episodePatternGI = /s(\d{1,2})e(\d{1,2})/gi;
var matches = 'S3E1 hehehe bla s09e12'.match(episodePatternGI);
var episodes = [];
var episodePatternI = /s(\d{1,2})e(\d{1,2})/i; // g modifier removed
matches.forEach(function(val) {
var ep = episodePatternI.exec(val); // New pattern applied
episodes.push({
s: ep[1],
e: ep[2]
});
});
console.log(episodes);
As you can see, in the second case I use the same pattern, but the g
modifier is removed.
Why doesn't the first case work?