Search code examples
javascriptregexxregexp

Can't able to figure out how to ensure last pattern


I'm not able to figure out how to ensure only content1 match and not content2.

var re  =  "//(\d{1,2})/";

var content1 = "/digital-cameras/point-shoot/10";
var content2 = "/digital-cameras/10-point-shoot";

How to check on end of line?


Solution

  • If you want one or two digits at the end, put $ at the end of the regular expression. Also, in JavaScript, regular expression literals are written with /.../, not "...":

    var re  =  /(\d{1,2})$/;
    // $ here -----------^
    

    There, the / at either end is not part of the expression, it marks the start and end of the expression (like " and ' do for strings).

    $ is called an "anchor" and it means "the end of the input." (There's another one, ^, which means "the beginning of the input.")