Remove plus sign (+) in URL query string

后端 未结 5 1761
失恋的感觉
失恋的感觉 2020-11-29 06:46

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

相关标签:
5条回答
  • 2020-11-29 06:53

    You can use replace() for this purpose

    var dateString = 'Friday+September+13th';
    var s = dateString .replace(/\+/g, ' ');
    
    0 讨论(0)
  • 2020-11-29 06:54

    Have you tried https://www.npmjs.com/package/querystring ?

    import { parse } from 'querystring'; 
    parse('ks4day=Friday+September+13th')
    

    returns

    { 'ks4day': 'Friday September 13th' }
    

    Assuming you are using something like Webpack that knows how to process import statements

    0 讨论(0)
  • 2020-11-29 06:59

    If that's what you are doing, the plus sign will not be the only one that is going to give you a hard time. The apostrophe ('), equals (=), plus (+) and basically anything not in the permitted URL characters (see Percent-encoding @ Wikipedia) is going to get escaped.

    What you are looking for is the decodeURIComponent function.

    0 讨论(0)
  • 2020-11-29 07:06

    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'
    
    0 讨论(0)
  • 2020-11-29 07:10

    Parsing strings using regex is often prone to so many errors. Thankfully all modern browsers provide URLSearchParams to handle params from url strings in a proper way:

    var params = new URLSearchParams(window.location.search);
    var value = params.get('ks4day');
    // "Friday September 13th"
    

    Ps: There is also a good polyfill for old browsers.

    0 讨论(0)
提交回复
热议问题