views:

52

answers:

1

Why is this giving me null?

<script language="javascript">
    var element     = "11";
    var string      = "7,11";
    var check       = string.match("/(^|\D)"+element+"(\D|$)/g");
    alert(check);
</script>

When I run the regex on http://regex.larsolavtorvik.com/ it works correctly.

Pleeeease help I want to sleeeep! :))

+3  A: 
var check       = string.match(new RegExp("(^|\\D)"+element+"(\\D|$)", "g"));

You have to escape the \ in the string literal, or the regex engine will see \D as D.

EDIT: Sorry, I should have read more carefully. You don't want the /es, and you need to handle /g separately.

Matthew Flaschen
I escaped it but it's still `null` :|
CIRK
Omg!!! omg!! Thanks thanks! I was looking at the error for hours!!! AAaaaAAaaaaAAa, I never seen using regex in this way in javascript before! I love you!!
CIRK
for the error**
CIRK