如何使用JavaScript或jQuery和正则表达式重写链接? [英] How can I rewrite links with JavaScript or jQuery and a regular expression?

查看:44
本文介绍了如何使用JavaScript或jQuery和正则表达式重写链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望修改Yahoo Answers链接以删除某些部分,仅保存qid并将index替换为answer.

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

所以这个:

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

成为这个:

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

我知道可以使用.htaccess重写链接,但是在这种情况下,它必须是Greasemonkey脚本,因为该任务将在我访问的网站而不是我的网站上完成.

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.

推荐答案

通常,应该这样做(完整的GM脚本):

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

这篇关于如何使用JavaScript或jQuery和正则表达式重写链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆