JavaScript DecodeURIComponent和.replace()不从URL中删除%20

时间:2015-08-04 12:57:52

标签: javascript url header uri urldecode

我的网址中有一个位置属性,我希望将其用作我网站上的标题。

我当前的网址如下所示:http://localhost:37675/Directory/Home?location=Carol%20Stream

这是我的标题:

<h2 id="cookie1" class="col-xs-offset-2 col-xs-10 col-sm-offset-4 col-sm-4 col-md-offset-5 col-md-3"></h2>

当我使用此JavaScript代码时:

    (function () {

        var myParam = location.search.split('location=')[1];
        myParam.replace(/%20/g, ' ');
        document.getElementById("cookie1").innerHTML = myParam;

    })();

我的标题如下:

JS 1

当我使用这个java脚本代码时:

    (function () {

        var myParam = location.search.split('location=')[1];
        decodeURIComponent(myParam);
        document.getElementById("cookie1").innerHTML = myParam;

    })();

我的标题仍然如下:

JS 1

为什么.replace或DecodeURIComponent都没有用空格替换我的网址中的%20?

我查看了这些堆栈交换帖子,但没有一个对我有用:

Javascript replace all "%20" with a space

Javascript - Replace '%20' spaces

JavaScript how to replace %20 to space

1 个答案:

答案 0 :(得分:0)

由于我正在使用MVC,我最终将该位置添加到视图包。

在我在控制器中返回视图之前,我添加了:

ViewBag.location = location;

并将我的JavaScript更改为:

    //function to retrieve location and place it in the header
    (function () {

        var location = "@ViewBag.location";

        //checks location length and if it is empty print "All Contacts" to the header else it prints the locaiton
        document.getElementById("cookie1").innerHTML = (location.length > 0)? location : "All Contacts" ;

    })();