JavaScript Regular Expression for Matching Strings

by Michael Cannon in Tech · 0 comments


Sometimes, using JavaScript’s own built-in objects really makes life easier for when the inline auto-typing constructs fail.

In the case that lead up to this tip, the typical JavaScript inline regular expression declaration failed for some painful to debug reason. Offender…

var cDay = /DAY/i;

This cDay declaration failed to match strings ‘DAY1′ and ‘DAY2′, but did correctly match strings ’2DAYS’ and ’2DAYSNS’.

Coming to the rescue is calling JavaScript RegEx object and using the exec method directly to fire off the regular expression checking with the given string value. Afterwards, check for a null value for no matches. Previously, I had used cValue’s Search method and looked for ‘counts’ in the result.

New working code.

var cDay = new RegExp('DAY');
for(i=1; i<= coursesCount; i++) {        
	id = 'course_'+i;
	if(document.getElementById(id).value != 0) {
	   allEmpty = false;
	var cValue = document.getElementById(id).value;
	var cResult = cDay.exec(cValue);
	if(null != cResult) {
		hasConference = true;

Now this method correctly matches strings ‘DAY1′, ‘DAY2′, ’2DAYS’ and ’2DAYSNS’.

Related Links

Be Sociable, Share!

Related Entries

About Michael Cannon

Hello, I'm Michael Cannon, Peichi's smiling man, an adventurous water-ratchief technology officer, cyclist, poet, WWOOF'er and world traveler.

Previous post:

Next post: