JavaScript RegExp object

JavaScript RegExp Object

RegExp: is the abbreviation of regular expression.

What is RegExp?

Regular expression describes the pattern object of characters.

When you retrieve some text, you can use a pattern to describe what you want to retrieve. RegExp is this pattern.

Simple pattern can be a single character.

More complex patterns include more characters and can be used for parsing, format checking, replacement, etc.

You can specify the search position in the string, the type of characters to be searched, etc.

Syntax

var patt=new RegExp(pattern,modifiers);

Or a simpler way

var patt=/pattern/modifiers;

Pattern describes an expression model. Modifiers describe whether the search is global, case-sensitive, etc.

Note: When using the constructor to create a regular object, regular character escaping rules are required (add a backslash \ in front). For example, the following are equivalent:

var re = new RegExp("\\w+");
var re = /\w+/;

RegExp modifier The

modifier is used to perform case-insensitive and full-text searches.

i - The modifier is used to perform case-insensitive matching.

g - The modifier is used to perform a full-text search (instead of stopping at the first one found, find all matches).

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<script>
var str = "Visit PHP.cn";
var patt1 = /PHP中文网/i;
document.write(str.match(patt1));
</script>
</body>
</html>

Full-text search and case-insensitive search for "is"

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<script>
var str="Is this all there is?";
var patt1=/is/g;
document.write(str.match(patt1));
</script>
</body>
</html>

test()

test() method Searches for a specified value in a string and returns true or false based on the results.

The following example searches for the character "e" from a string:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<script>
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
</script>
</body>
</html>

exec()

The exec() method retrieves a specified value from a string. The return value is the found value. If no match is found, null is returned.

The following example searches for the character "e" from a string:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<script>
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
</script>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> ​ <script> var str="Is this all there is?"; var patt1=/is/g; document.write(str.match(patt1)); </script> ​ </body> </html>
submitReset Code