NathanZ
NathanZ

Reputation: 13

What does a string delimited by forward slashes (`/ … /`) mean in JavaScript?

What does this do?

var INTEGER_SINGLE = /\d+/;

What do the forward slashes mean? How about the backslash? Does d mean digit?

Upvotes: 1

Views: 71

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83358

That creates a regular expression that matches one or more digits.

Anything inside / / is a regular expression. \d matches a digit, and + is the positive closure, which means one or more.


Having said that, depending on what this regex is supposed to do, you may want to change it to:

var INTEGER_SINGLE = /^\d+$/;

^ matches the beginning of the string, and $ the end. The end result would be that any strings you try to match against the regex would have to satisfy it in the string's entirety.

var INTEGER_SINGLE = /^\d+$/;

console.log(INTEGER_SINGLE.test(12));    //true
console.log(INTEGER_SINGLE.test(12.5));  //false

Of course if the regex is supposed to only match a single integer anywhere in the string, then of course it's perfect just the way it is.

Upvotes: 4

Related Questions