正则表达式删除URL中的所有特殊字符

时间:2011-09-22 07:29:53

标签: javascript regex

我需要基本清理包含特殊字符的网址,如下所示:

http://172.23.113.79/recherche/pages/Results.aspx?k=**cr%c3%83%c2%a9er***

我想将**cr%c3%83%c2%a9er***替换为**créer**

以及更常见的所有字符,例如À Á Â à á â È É Ê è é ê Ì Í Î ì í î Ò Ó Ô ò ó ô Ù Ú Û ù ú û

3 个答案:

答案 0 :(得分:4)

var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=cr%c3%83%c2%a9er*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=créer*"

var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=cr%C3%A9er*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=créer*"

var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=%C3%A9%C3%A8%C3%A0%C3%A7%C3%B9%C3%A2%C3%AA%C3%AE*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=éèàçùâêî*"

了解更多:

MDN decodeURI:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURI

MDN decodeURIComponent:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent

 var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=%C3%80%C3%81%C3%82%C3%A0%C3%A1%C3%A2%C3%88%C3%89%C3%8A%C3%A8%C3%A9%C3%AA%C3%8C%C3%8D%C3%8E%C3%AC%C3%AD%C3%AE%C3%92%C3%93%C3%94%C3%B2%C3%B3%C3%B4%C3%99%C3%9A%C3%9B%C3%B9%C3%BA%C3%BB*");
 // u is "http://172.23.113.79/recherche/pages/Results.aspx?k=ÀÁÂàáâÈÉÊèéêÌÍÎìíîÒÓÔòóôÙÚÛùúû*"

答案 1 :(得分:0)

如果它不是非常通用的并且你有特殊的字符和短语要替换,你可以将你的特殊字符/短语映射到它们的替换,然后解码字符串并替换它们中的每一个:

var replacements = {
    "créer" : "créer", // this is a phrase
    "Ã" : "é",
    "Â" : "e",
    "©" : ""
};
var url = "http://172.23.113.79/recherche/pages/Results.aspx?k=**cr%c3%83%c2%a9er***";
var decoded = unescape(url); // or decodeURI(url);
for(var key in replacements)
    decoded = decoded.replace(key,replacements[key]);

答案 2 :(得分:0)

使它更通用

if (jQuery.browser.msie) {
                retStr = encodeURI(retStr);
            }