简体   繁体   English

如何用JavaScript或jQuery和正则表达式重写链接?

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

Looking to modify Yahoo Answers links to remove some parts, saving just the qid and replacing index with answer . 想要修改Yahoo Answers链接以删除一些部分,只保存qid并用answer替换index

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. 我知道有办法用.htaccess重写链接,但在这种情况下,它需要是一个Greasemonkey脚本,因为任务将在我访问的网站上完成,而不是我的网站。

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. 不过我对Greasemonkey并不是很了解,所以我不能给你更多。 Hopefully someone with more knowledge of Greasemonkey comes along and provides a better answer. 希望有更多Greasemonkey知识的人出现并提供更好的答案。

In General, this should do it ( Complete GM script ): 总的来说,这应该这样做( 完整的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;
    }
} );

Replace 更换

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

with

"$1/answer?quid=$2"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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