Categories
Coding Javascript

Where URLSearchParams fail

I’ve been working on a project, and one of the functions needs to get the parameters from the URL. Since IE compatibility wasn’t a requirement, I decided to use the URLSearchParams interface.

const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('firstname') && urlParams.has('lastname') && urlParams.has('email') && urlParams.has('subs') && urlParams.has('unsubs')) {
const firstName = urlParams.get('firstname');
const lastName = urlParams.get('lastname');
const email = urlParams.get('email');
const subs = urlParams.get('subs');
const unsubs = urlParams.get('unsubs');
}

And this seemed to work fine, until I got to the testing phase.

Where it falls down is if you have special characters, like a ‘+’ in one of the parameters (like an email field). The value returned from the .get() method strips the special character out of the string and replaces it with a space. Frustrating.

So I had to abandon using the new hotness and fall back to using good old regex for getting the values.

getParameterByName(url, name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null) {
return null;
}
return decodeURI(results[1]) || 0;
}
// usage
getParameterByName(window.location.href, 'email')

If I did’t have to deal with email addresses that allow special characters, I would have loved to use URLSearchParams. The future is bright, but unfortunately it’s not perfect.