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
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));

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.