Jeeva Raam
Jeeva Raam

Reputation: 47

How to use if condition in Javascript RegEx?

I am trying to add some rules to Imagus Firefox Extension. I want to capture image parameter from Google Image Search and if it contains the string th_ remove it and redirect. Otherwise just redirect.

This is my RegEx:

/^(?:(?:images|encrypted)\.)?google\.[^/]+/(?:imgres\?(?:[^&]+&)*?imgurl=)(.*)(?:th_)(.*)&imgrefurl=.*/gm

It works fine for URL's which contain string th_ but for other links it breaks.

Here's the link to my work https://regexr.com/3omf5 Have a look and help.

PS: Please note there are two links in the example.

Upvotes: 1

Views: 100

Answers (3)

Jeeva Raam
Jeeva Raam

Reputation: 47

I found the answer after a fight. And the regex works fine in the Extension.

Ans:

^(?:(?:images|encrypted)\.)?google\.[^/]+/(?:imgres\?(?:[^&]+&)*?imgurl=)(.*)(%2Fimages(?:[\d]{1,9})?%2F)(th_)?(.*)&imgrefurl=.*

Here is th link with answer:
https://regexr.com/3omfh

Upvotes: 2

Chrᴉz remembers Monica
Chrᴉz remembers Monica

Reputation: 1904

^(?:(?:(?:images|encrypted)\.)?google\.[^/]+/(?:imgres\?(?:[^&]+&)*?imgurl=)(.*)(?:th_)(.*)&imgrefurl=.*)|(.+)

Matches your urls with th_ and replaces it or takes the whole url with the additional |(.+) (+ ^(?: ... ) around your regex). You need to replace it with $1$2$3 then

Upvotes: 0

Guilherme Lemmi
Guilherme Lemmi

Reputation: 3487

Add a * after (?:th_), like:

^(?:(?:images|encrypted)\.)?google\.[^/]+/(?:imgres\?(?:[^&]+&)*?imgurl=)(.*)(?:th_)*(.*)&imgrefurl=.*

Upvotes: 0

Related Questions