使用 JavaScript 删除非法 URL 字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3486625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove illegal URL characters with JavaScript
提问by Peter
I have an array filled with strings, a value can for example be "not updated for > days". I use the values in the array to create some url's and need to remove the /\<> and other illegal URL characters. How do I easiest do this?
我有一个填充字符串的数组,例如一个值可以是“未更新 > 天”。我使用数组中的值来创建一些 url,并需要删除 /\<> 和其他非法 URL 字符。我如何最简单地做到这一点?
I started with
我开始了
var Name0 = title[0].substring(1).replace(" ", "%20").replace("/", "") + '.aspx';
var Name1 = title[1].substring(1).replace(" ", "%20").replace("/", "") + '.aspx';
and so on but can I do this in a better way?
Thanks in advance.
提前致谢。
回答by Delan Azabani
If you wish to keep the symbols in the URI, but encode them:
如果您希望将符号保留在 URI 中,但对其进行编码:
encodedURI = encodeURIComponent(crappyURI);
If you wish to build 'friendly' URIs such as those on blogs:
如果您希望构建“友好”的 URI,例如博客上的 URI:
niceURI = crappyURI.replace(/[^a-zA-Z0-9-_]/g, '');
回答by Darin Dimitrov
You could use the encodeURIComponentfunction which will properly URL encode the value.
您可以使用encodeURIComponent函数来正确地对值进行 URL 编码。
回答by Russ Cam
Have you had a look at encodeURIComponent?
你看过encodeURIComponent吗?
Example usage
示例用法
var encoded = window.encodeURIComponent("http://stackoverflow.com/questions/3486625/remove-illegal-url-characters-with-javascript/3486631#3486631");
// encoded contains "http%3A%2F%2Fstackoverflow.com%2Fquestions%2F3486625%2Fremove-illegal-url-characters-with-javascript%2F3486631%233486631"

