How to replace plus (+) signs with spaces ( ) in GET parameters with javascript

心不动则不痛 提交于 2021-01-29 12:56:54

问题


I get users redirected to my site with GET parameters like this: www.example.com/?email=mail@mail.com&vorname=name1+name2

I use javascript to populate my texfields (newsletter subscription) like this:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}

var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');

document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;

Like this it works properly but the parameter "vornametxt" contains plus signs if the GET parameter contains them. I want to replace the plus signs in the names with spaces which should work like this:

vornametxt = vornametxt.replace(/\+/g, " ");

That's what I found in older questions on stack overflow but it doesn't work. What am I doing wrong? Is it possible that my wordpress site doesn't allow certain code?

I am using Wordpress and a plugin which allows me to add this javascript code to my sites footer.


回答1:


Those values are URI-encoded with + meaning "space". To decode them, replace + with space and then use decodeURIComponent (to handle any other chars that have been encoded). I think it would go in your getUrlParam function, right at the end:

return decodeURIComponent(urlparameter.replace(/\+/g, " "));

Live Example:

(function() {
    var window = {
        location: {
            href: "http://www.example.com/&email=mail@mail.com&vorname=name1+name2"
        }
    };

    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    }
  
    function getUrlParam(parameter, defaultvalue){
        var urlparameter = defaultvalue;
        if (window.location.href.indexOf(parameter) > -1) {
            urlparameter = getUrlVars()[parameter];
        }
        return decodeURIComponent(urlparameter.replace(/\+/g, " "));
    }
  
    var vornametxt = getUrlParam('vorname','');
    var emailtxt = getUrlParam('email','');
  
    document.querySelector("input[name=nn]").value = vornametxt;
    document.querySelector("input[name=ne]").value = emailtxt;
})();
<input type="text" name="nn">
<br><input type="text" name="ne">


来源:https://stackoverflow.com/questions/51730730/how-to-replace-plus-signs-with-spaces-in-get-parameters-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!