This is the 18th day of my participation in the More text Challenge. For more details, see more text Challenge

What is a regular expression?

Regular Expression (RegExp for short) is a syntax rule that describes the structure of a string. Matches a series of string search patterns that match a syntactic rule. Search mode can be used for text search and text replacement.

There are two common regular expressions:

One is POSIX specification compliant regular expressions to ensure portability between operating systems. One is Perl regular expressions, which are perl-based regular expressions in JavaScript.Copy the code

How to use regular expressions

Regular expression syntax

/ Regular expression body/modifier (optional) Here’s an example:

<script> var reg = /gW/i; // I is a modifier that means case is ignored </script>Copy the code

Regular expression modifier

G is used to achieve global matching in the target string I ignores case M implements multi-line matching U performs a regular expression y in Unicode encoding, matching only the index indicated by the lastIndex property of this regular expression in the target stringCopy the code

Regular expression methods

A regular expression can search for matches using the exec() method provided by the RegExp object and the match() method provided by the String.

The exec method

The exec method is used to search for matches in the target string, returning an array with only one match at a time.

<script> var str = 'sfvnslgkslgscutoscwt'; var reg = /sc/i; // Define the regular expression console.log(reg.exec(STR)); </script>Copy the code

The first element of the array is the matched string, the second is the subscript, and the third is the target string.

The match method

The match method can not only retrieve the value matching the condition in the string, but also match all the required content in the target string according to the regular expression.

<script> var str = 'sCfvnslgkslgScutoscwt'; var reg = /sc/gi; Var reg2 = /^sc/gi; Var reg3 = /sc$/gi; Console. log(str.match(reg)); console.log(str.match(reg2)); console.log(str.match(reg3)); </script>Copy the code

The start and end positions here represent strings that start with sc, and strings that end with sc. You can take a look at it.