Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

javascript - Remove plus sign (+) in URL query string

I am trying get the string in the following URL to display on my webpage.

http://example.com?ks4day=Friday+September+13th

EDIT: The date in the URL will change from person to person as it's merged in by my CRM program.

I can get it to display on my webpage using the code below, the problem is the plus signs (+) come through as well.

eg. Friday+September+13th

What I need it to do is replace the plus signs (+) with spaces so it looks like this:

eg. Friday September 13th

I'm new to this so I'm having some trouble working it out.

Any help would be appreciated.

This is the code i'm using in a .js file

      function qs(search_for) {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i=0; i<parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0  && search_for == parms[i].substring(0,pos)) {
            return parms[i].substring(pos+1);;
        }
    }
    return "";
}

This is the code i'm using on my webpage to make it display

     <script type="text/javascript">document.write(qs("ks4day"));</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although Bibhu's answer will work for this one case, you'll need to add decodeURIComponent if you have encoded characters in your URI string. You also want to make sure you do the replace before the decode in case you have a legitimate + in your URI string (as %2B).

I believe this is the best general way to do it:

var x = qs("ks4day");        // 'Friday+September+13th'
x = x.replace(/+/g, '%20'); // 'Friday%20September%2013th'
x = decodeURIComponent(x);   // 'Friday September 13th'

Here's an example of when it might be useful:

var x = '1+%2B+1+%3D+2'; 
x = x.replace(/+/g, '%20'); // '1%20%2B%201%20%3D%202'
x = decodeURIComponent(x);   // '1 + 1 = 2'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...