使用JavaScript删除非法URL字符

时间:2010-08-15 07:53:27

标签: javascript jquery

我有一个填充了字符串的数组,例如,值可以“未更新为>天”。我使用数组中的值来创建一些网址,并需要删除/ \<>和其他非法的URL字符。我最容易做到这一点?

我从

开始
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?

提前致谢。

3 个答案:

答案 0 :(得分:50)

如果您希望将符号保留在URI中,请对其进行编码:

encodedURI = encodeURIComponent(crappyURI);

如果您希望构建“友好”URI,例如博客上的URI:

niceURI = crappyURI.replace(/[^a-zA-Z0-9-_]/g, '');

答案 1 :(得分:2)

您可以使用encodeURIComponent函数来正确对值进行URL编码。

答案 2 :(得分:1)

你看过encodeURIComponent吗?

使用示例

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"
相关问题