Extracting a Specific Parameter from a URL Query String with a Regular Expression
Internet Explorer doesn’t support URLSearchParams. That makes dealing with URL query strings a hassle.
Adding a polyfill or writing a separate function to pull out the query string are both good approaches, but depending on the situation there are times when you just want to grab the value of a specific key in a single line of code.
So I put together some code that extracts the value of a specific key from the query string using a simple regular expression and a replace statement.
// Change 'key' in the code below to pull out the value you want
var wantedParam = /[a-zA-Z0-9_-]*/.exec(window.location.search)[0].replace("&key=", "").replace("key=", "");
It’s a bit clunky, but it works fine.
If you want to keep it even simpler, this works too.
// Change 'key' in the code below to pull out the value you want
window.location.search.match(/key=([^&]*)/)[1];
Since it’s hardcoded you might get some flak for it, so use it with care.
- Reference: URLSearchParams browser compatibility
Leave a comment