javascriptregexliterals

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?


Solution

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