简体   繁体   中英

Javascript Regex - \\d works but not \d

So im trying some really basic RegEx out for the first time and i've been told that ' \\d ' denotes a digit match.

Please can someone explain why only pattern 1 below with a double back-slash " \\\\d " works when in theory it shouldn't.

After looking in the Javascript Regular Expressions documentation, they also include the rogue back slash when you follow this link .

var str = "123456",
    pattern1 = new RegExp("^\\d{6}$"),
    pattern2 = new RegExp("^\d{6}$");

if(pattern1.test(str)){
    alert('pattern 1 match!'); 
}else{
    alert('pattern 1 no match!'); 
}

if(pattern2.test(str)){
    alert('pattern 2 match!'); 
}else{
    alert('pattern 2 no match!'); 
}

You do not need to wrap a regular expression in quotes if you lead and end with /

pattern2 = new RegExp(/^\\d{6}$/);

The extra \\ is needed because it escapes the other \\

In JavaScript the backslash \\ is a special escape character. To represent a backslash in a JavaScript string you must use two \\\\ .

See documentation at MDN

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM