Question

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?

Was it helpful?

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.")

OTHER TIPS

Escape forward slashes and use end of line anchor $ to make sure digits are matched at line end only:

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

You can match against the end-of-string, using the $ anchor:

/(\d{1,2})$/

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top