簡體   English   中英

如何用JavaScript或jQuery和正則表達式重寫鏈接?

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

想要修改Yahoo Answers鏈接以刪除一些部分,只保存qid並用answer替換index

所以這:

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

成為這個:

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

我知道有辦法用.htaccess重寫鏈接,但在這種情況下,它需要是一個Greasemonkey腳本,因為任務將在我訪問的網站上完成,而不是我的網站。

你需要的模式是這樣的:

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

而你用這個代替它:

/$1answer$2/

不過我對Greasemonkey並不是很了解,所以我不能給你更多。 希望有更多Greasemonkey知識的人出現並提供更好的答案。

總的來說,這應該這樣做( 完整的GM腳本 ):

// ==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;
    }
} );

更換

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

"$1/answer?quid=$2"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM