Regex + Javascript: pitfalls concerning dot, backslash and others



console.log("====== ^ and $ ====="); 

console.log(/a/.test("abc"));     //true
console.log(/^a$/.test("abc"));   //false. Add ^ ad $ to confirm a non-partial match

console.log("====== dot ====="); 
console.log(/^.$/.test("a"));     //true.  A dot means any character
console.log(/^\.$/.test("a"));    //false.  \. means dot 
console.log(/^\.$/.test("."));    //true.    \. means dot

console.log(/^[.]$/.test("a"));    //false.  A dot in brackets means a real dot 
console.log(/^[.]$/.test("."));    //true.   A dot in brackets means a real dot
console.log(/^[\.]$/.test("a"));    //false. \. in brackets also means a real dot
console.log(/^[\.]$/.test("."));    //true.  \. in brackets also means a real dot


console.log("====== comma ====="); 
console.log(/^,$/.test("a"));     //false.  A comma just means a comma
console.log(/^\,$/.test("a"));    //false.  \, just means a comma 
console.log(/^\,$/.test(","));    //true.    \, just means a comma

console.log(/^[,]$/.test("a"));    //false.  A comma in brackets just means a comma 
console.log(/^[,]$/.test(","));    //true.   A comma in brackets just means a comma
console.log(/^[\,]$/.test("a"));    //false. \, in brackets just means a comma
console.log(/^[\,]$/.test(","));    //true.  \, in brackets just means a comma  


console.log("====== space ====="); 
console.log(/^ $/.test(" "));     //true
console.log(/^\s$/.test(" "));     //true
console.log(/^[ ]$/.test(" "));    //true
console.log(/^[\ ]$/.test(" "));   //tru
var reg = new RegExp("^\.$"); 
console.log(reg);  // =   /^.$/ , so in a string we should escape backslash, otherwise javascript will treat \. as . 
console.log(reg.test("a"));  //true  
console.log(reg.test("."));  //true 


var reg = new RegExp("^\\.$"); 
console.log(reg);  // =  /^\.$/  , so in string we should escape backslash. \\ will finally be \
console.log(reg.test("a"));  //false
console.log(reg.test("."));  //true
e
console.log(/^[\s]$/.test(" "));   //true


console.log("Shall we escape backslash in a string?"); 

 
var reg = new RegExp("^\.$"); 
console.log(reg);  // =   /^.$/ , so in a string we should escape backslash, otherwise javascript will treat \. as . 
console.log(reg.test("a"));  //true  
console.log(reg.test("."));  //true 


var reg = new RegExp("^\\.$"); 
console.log(reg);  // =  /^\.$/  , so in string we should escape backslash. \\ will finally be \
console.log(reg.test("a"));  //false
console.log(reg.test("."));  //true



Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.