Thanks to modern browsers, writing cross-browser compatible JavaScript isn’t nearly as difficult as it was even just a few years ago; however, there are still times when you get cryptic error messages such as “invalid regular expression flag.”

Just as Jamie Zawinski said:

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

It’s funny because it’s true, right? But we still have regular expressions, they’re still powerful, and we still use them.

Unfortunately, there are still times in which they can plague us when working with JavaScript, string replacement, and modern web browsers.

The Use Case

Earlier this week, I was working on a project in which a user would be making a selection from a `select` box.

I had an event handler attached to `select` element’s `onchange` event so that when the user made their selection, the DOM would be manipulated in such a way that certain elements would have their spaces replaced with a hyphen.

Specifically, the original code looked something like this:

var sLocation;
$('#locations').on('change', function() {

	sLocation = $(this).val().toLowerCase();
	sLocation = sLocation.replace( ' ', "-", sLocation );

	// irrelevant code removed...

});

Now, up until a certain point in testing I had no problem with this. In fact, it was working fine in WebKit based browsers, but it tanked in Firefox.

Invalid Regular Expression Flag

Invalid Regular Expression Flag

Of course, this is really a manifestation of laziness or forgetfulness (I’d much rather assume the latter) on my part because the method signature for `replace` is `regex/substr, newString`.

Although certain implementations of JavaScript will support a substring (like what I had originally), a regular expression is the more widely accept method.

As such, it required a change to the code as follows:

var sLocation;
$('#locations').on('change', function() {

	sLocation = $(this).val().toLowerCase();
	sLocation = sLocation.replace( /s+/gm, "-", sLocation );

	// irrelevant code removed...

});

And thus, the problem was resolved.

So What’s The Deal?

As I mentioned, it really depends on the browsers implementation of the JavaScript interpreter, but here’s a more literal way of looking at it:

  • The first version of the code was saying “replace all substring spaces with a hyphen.”
  • The second version has a regular expression that says “replace any occurrence of a space that occurs globally in the string.”

There’s obviously very little difference in the two implementations, but – again – it all comes down to the implementation of JavaScript.

If regular expressions are the argument accepted in a function signature, then that’s the one you’ve gotta use. Unless, of course, you’re only building for WebKit based browsers, but that’s an entirely other post.