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?
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.")
转义正斜杠,并使用行尾锚$
来确保数字仅在行尾匹配:
var re = "/\/\d{1,2}$/";
You can match against the end-of-string, using the $
anchor:
/(\d{1,2})$/
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.