I have a question about doing something in regular expressions, is this possible, and if so, how.
Summary of what I do: I read Manga online. I like to open the current problem in a new tab, but I do not always remember to click the link with a middle click.
So, I decided to write a Greasemonkey script that will run on any of the site pages, adding target="_blank" to any anchor tag that refers to a manga or a problem with this manga, so a normal click will open it in a new tab. The script itself works fine, nothing is impressive.
Now for the caveat:
Sample links that we will name for each manga are as follows
<language of manga>/<manga name> links to the main about page for the manga <language of manga>/<manga name>/<issue number> links to the issue number itself <language of manga>/<manga name>/<issue number>/<page number> links to the specific page of the issue
Now I want him to always make the first two open in a new tab, but I DO NOT want the last two to open in a new tab. The reason for this is that when you read the actual Manga, each click to advance the page will open a new tab.
So, for this I have two regular expressions:
var MangaIssueRegex = /en-manga\/[A-Za-z0-9\-]+\//; var MangaIssuePageRegex = /en-manga\/[A-Za-z0-9\-]+\/(\d+\/){2}/
The first regular expression selects any of the three manga link patterns. The second regular expression selects only the third manga link template (one that is for a specific page).
In a nutshell, the Greasemonkey script goes through all the anchor tags on the page when it loads, and if the href attribute of the anchor tag passes MangaIssueRegex and the MangaIssuePageRegex fails, the anchor tag changes to open in a new tab, otherwise the anchor tag will not be changed.
Now you can combine both regular expressions into one that will correspond to the first two patterns, but will not work if a third pattern is found?
Here is the whole script:
var MangaIssueRegex = /en-manga\/[A-Za-z0-9\-]+\//; var MangaIssuePageRegex = /en-manga\/[A-Za-z0-9\-]+\/(\d+\/){2}/ var elements = document.getElementsByTagName("a"); for (var i = 0; i < elements.length; i++) { if (MangaIssueRegex.test(elements[i].getAttribute("href")) && !MangaIssuePageRegex.test(elements[i].getAttribute("href"))) { elements[i].setAttribute("target","_blank"); elements[i].setAttribute("title","Opens in another tab"); } }
Update
Thanks to both @DanielHilgarth and @iMoses for helping me figure this out.
I found out that I can use jQuery in Greasemonkey, so in the end this is what I ended up with a full working script
$("a") .filter(function(){return /en-manga\/[\w\-]+\/(\d+\/)?$/.test(this.href);}) .each(function(index){$(this).attr({title:"Opens in new tab",target:"_blank"});});