views:

37

answers:

2

Hi all I have the following Regx that can't be accepted on the JavaScript

if ($(caller).attr('value').toString().search('/(?=\D*\d\D*\d).{8,15}/g') == -1)

where

$(caller).attr('value').toString() = "fdsddfsd45"

it returns to me -1

also I'm try to test it from pattern

  if (!pattern.test($(caller).attr('value'))) {

where

pattern = /^(?=D*dD*d).{8,15}$/

it returns to me false

$(caller).attr('value').toString() = "fdsddfsd45"

when I tried to test it through desktop application called RegExr this string "fdsddfsd45" match the expression (?=\D*\d\D*\d).{8,15} is this JavaScript bug I don't know ?

+2  A: 

In JavaScript the regex should either be a string or a regex literal. In your case, this should do it:

.search(/(?=\D*\d\D*\d).{8,15}/) == -1

Note that I removed the single quotes. I've also remove the /g flag - since you are searching for any match, you don't need it.

For completeness, while it less useful, you could have written the regex as a string, but you'd have to escape all backslashes, or JavaScript will parse \d as d before it even reaches the regex. In this case, you don't need the slashes (unlike PHP, for example, which uses both):

s.search('(?=\\D*\\d\\D*\\d).{8,15}')

Example: http://jsbin.com/ubuce3

Kobi
A: 
"fdsddfsd45".search(/^(?=\D*\d\D*\d).{8,15}$/g)

will return 0, be careful the "'" character!

and

/^(?=\D*\d\D*\d).{8,15}$/.test("fdsddfsd45")

will return true!