Andy Crouch - Code, Technology & Obfuscation ...

Regex Use

Black And White Giraffe

Photo: Unsplash

Regex’s hit the headlines recently when someone wrote an article on their performance. I don’t remember the exact details but they turned code that took days to run into hours by removing the regex implementation.

Regex’s have their place. But most (non-Perl) developers don’t use them often enough to know how to use them correctly. Be honest when was the last time you used one without an ample amount of Googling?

I came across an example today. I couldn’t remember off the top of my head how to get an URL parameter in JavaScript. Every example I came across did something very similar to

var parseQueryString = function(url) {
  var urlParams = {};
  url.replace(
    new RegExp("([^?=&]+)(=([^&]*))?", "g"),
    function($0, $1, $2, $3) {
      urlParams[$1] = $3;
    }
  );
  
  return urlParams;
}

Now, I am not saying this is wrong but using Regex’s for something like this feels like cracking a nut with a sledgehammer.

After searching my notes I found the following solution

function getUrlParameterFrom(url, parameterKey) {
    var url = new URL(url);
    return url.searchParams.get(parameterKey);
}

(If you don’t want to pass URL, you can just substitute for window.location)

Isn’t that a cleaner solution using the available functionality of the language/framework? No need to Google and figure out the pattern you need. Simple to read. Easy.

What’s your views on Regular Expressions? Do you use them frequently? Message me via twitter or email to discuss.