How can I rewrite links with JavaScript or jQuery and a regular expression?

旧街凉风 提交于 2019-12-11 08:26:33

问题


Looking to modify Yahoo Answers links to remove some parts, saving just the qid and replacing index with answer.

So this:

http://answers.yahoo.com/question/index;_ylt=AhT5ZZwbMiGWdQZDSxD1ML305nNG;_ylv=3?qid=20121004094847AAjekoj

becomes this:

http://answers.yahoo.com/question/answer?qid=20121004094847AAjekoj

I know there are ways to rewrite links with .htaccess but in this case, it would need to be a Greasemonkey script since the task would be done on sites I visit, and not my websites.


回答1:


In General, this should do it (Complete GM script):

// ==UserScript==
// @name     _Replace yahoo-answers links
// @include  http://answers.yahoo.com/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change introduced
    in GM 1.0.   It restores the sandbox.
*/
var targLinks   = $("a[href*='question/index']");
targLinks.each ( function () {
    if (/\bqid=\w+/i.test (this.href) ) {
        var newHref = this.href

        var newPath = this.pathname.replace (/\/question\/index.+$/, "/question/answer");
        var newURL  = this.protocol + "//"
                    + this.host
                    + newPath
                    + this.search
                    + this.hash
                    ;
        this.href   = newURL;
    }
} );



回答2:


The pattern you need here would be this:

/(http:\/\/answers.yahoo.com\/questions\/)index.*(?qid=.*)$/i

And you'd replace it with this:

/$1answer$2/

I don't really know a lot about Greasemonkey, though, so I can't give you more than this. Hopefully someone with more knowledge of Greasemonkey comes along and provides a better answer.




回答3:


Replace

/(http:\/\/answers\.yahoo\.com\/question)\/index.+[?&]qid=([^&#]+)/g

with

"$1/answer?quid=$2"


来源:https://stackoverflow.com/questions/12731801/how-can-i-rewrite-links-with-javascript-or-jquery-and-a-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!