kiwix-js
kiwix-js copied to clipboard
Use regular expression literals when it's more readable
I had the habit (coming from other languages) to externalize regular expressions as variables created from a string, to make sure they were compiled once for all. But there seems to be a better way in javascript. Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions, the regexp is compiled only once (when the script is loaded) when you use a literal.
When the regexp is not complicated, I find it more readable to put it as a literal when you need it. And it's still possible to create a variable if it's used several times. In this case, a literal makes the regexp compiled when the script is loaded instead of when it's executed.
There's not a huge difference according to https://jsperf.com/regexp-indexof-perf. The real winner is indexOf (when you don't actually need a regex, just a match), which can be used as ~url.indexOf('.svg') for a quick true/false match (because indexOf returns -1 if not found, the tilde ~ turns -1 to 0). Of course we can't actually use that because, for example, there are some image url's like thisLovelyImage.svg.png which would falsely match against that example. But we're talking about 2 million matches per second in most Regex scenarios: any speed gain of any particular method is not going to be noticed by a human. Regexes are pretty damn fast however you use them!
We already take this into account.