A mistake with RegExes in JavaScript

In the past months I've made a subtle JavaScript programming error repeatedly. In an effort to not make this mistake again, I'll discus this error here.

Very often I write statements such as the following:

if (myString.search(/lorem/)) {
}

(Of course, the actual regex used differs).

According to the documentation, the search method expects a RegEx object. A RegEx object is conveniently created on the fly using the // shorthand. If you write it like I did above, all is well. However, I also frequently program in other languages where such a shorthand is not available. For example, in PHP you would write something like the following:

if (preg_match('/lorem/', $myString)) {
}

Note the apostrophes, because in PHP you specify the RegEx as a string.

Now, the problem is that I sometimes erroneously add the apostrophes when writing JavaScript code. But what does the following do?

if (myString.search('/lorem/')) {
}

Now JavaScript will see that it's an actually string and perform a case-sensitive search. So save yourself some trouble and always check that you're using a RegEx object (when you want of course).

No comments yet

Post new comment

The content of this field is kept private and will not be shown publicly.