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
You can use replace() for this purpose
var dateString = 'Friday+September+13th';
var s = dateString .replace(/\+/g, ' ');
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
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.
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'
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.