简体   繁体   中英

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.

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

(?:th_)之后添加* ,例如:

^(?:(?:images|encrypted)\.)?google\.[^/]+/(?:imgres\?(?:[^&]+&)*?imgurl=)(.*)(?:th_)*(.*)&imgrefurl=.*
^(?:(?:(?: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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM