使用 JavaScript 解码 URL 参数 [英] Decoding URL parameters with JavaScript

查看:27
本文介绍了使用 JavaScript 解码 URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是一个简单的任务,但我似乎找不到解决方案.

This should be a simple task, but I can't seem to find a solution.

我有一个基本字符串,它作为查询字符串参数传递,如下所示:This+is+a+message+with+spaces.我想使用 JavaScript 将该参数解码为 This is a message with space,但我似乎无法解码.

I have a basic string that is being passed through as a query string parameter like this one: This+is+a+message+with+spaces. I would like to decode that parameter using JavaScript to This is a message with spaces, but I cannot seem to get it to decode.

我试过 decodeURI('This+is+a+message+with+spaces') 但结果仍然包含 + 符号.

I've tried decodeURI('This+is+a+message+with+spaces') but the result still contains the + signs.

推荐答案

是的,decodeURIComponent 函数不会将 + 转换为空格.所以你必须使用替换函数替换 +.

Yes it is true that decodeURIComponent function doesn't convert + to space. So you have to replace the + using replace function.

理想情况下,以下解决方案有效.

Ideally the below solution works.

var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/+/g, '%20'));

这篇关于使用 JavaScript 解码 URL 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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