Javascript regexp whitespace matching by object created using RegExp constructor

Please study this code. Why does creating the same regular expression in different ways (via / regex / literal and the RegExp constructor) produce a different result? Why doesn't the second pattern match the space in str ?

var str = " "; var pat1 = /\s/; document.writeln(pat1.test(str)); // shows "true" var pat2 = new RegExp("\s"); document.writeln(pat2.test(str)); // shows "false" 

Unable to find the answer to my question anywhere. Thanks

+6
source share
1 answer

You need to avoid the backslash as it is on the line:

 var pat2 = new RegExp("\\s"); 
+18
source

Source: https://habr.com/ru/post/894843/