Jump to content

Interesting RegEx bug - String.Match()


Omirion

Recommended Posts

Hey,

I found something interesting.

 

When matching a RegEx literal against a string if your match fails the String.match() function returns an Object.

The JS reference clearly states the it's supposed to return null on fail.

 

I ran a for..in on it a got these key/value pairs.

 

| key | Typeof value | value

0          string

index    number          0

input    string            px

 

Here is the setup.

$(document).ready(function () {
		var a = "px";
		var b = a.match(/\d*/);
		for (v in b) {
			document.writeln(v + "  " + typeof b[v] + "  " + b[v])
		}
	})

Tested on FF 6 and Chrome.

 

Should i report this or am i missing something so hard i should stop coding for today...

Link to comment
https://forums.phpfreaks.com/topic/245311-interesting-regex-bug-stringmatch/
Share on other sites

First, null is an object, so keep that in mind.

 

Second, your regular expression finds a value and return it (eventhough it's an empty value), * will check for Zero or more matches (even 0 digits will return a value). You can use the + sign to check for at least on digit.

 

If you are trying to get the number out of a CSS value, the easiest way is to use parseInt(val, rdx),

e.g.

alert(parseInt('15px', 10));

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.