There are two ways to use regular expressions in JavaScript. The first is to build a RegExp object, and the second is to use "//" to define the Perl style. For example:
The code is as follows |
Copy Code |
var str = ' http://www.111cn.net/'; var reg = new RegExp (' http ', ' I '); Alert (Reg.test (str)); Or Alert (/http/.test (str)); |
The above example is to use two ways to determine if the string str contains HTTP, note the second way//must not use quotes.
The first way to generate an object is that the argument is a string, so you can set the contents of the regular expression dynamically (string concatenation), and the second does not. We know that there are many special characters in the regular expression, such as., *,?, and so on, if you need to match these special characters in an expression, you need to use the escape character "". In particular, it is necessary to use two "" when the first type of escape character is handled. For example:
The code is as follows |
Copy Code |
var str = ' http://www.111cn.net/'; var reg = new RegExp (' www\. ', ' I '); Two are used here Alert (Reg.test (str)); Or Alert (/www./.test (str)); |
So why use \ to escape? Because the first method is "compiled", it will become the second way. For example, alert (New RegExp (' www\. ', ' I ')) results in/www./i.