JavaScript advanced regular expression

#1, What is a regular expression

Regular expressions are patterns used to match character combinations in strings.
Regular expressions are often used to retrieve and replace text that conforms to a pattern.

2, Regular expressions are used in JavaScript

Using RegExp objects to create regular expressions

var regexp = new RegExp(/ expression /);

Create by literal

var variable name = / expression /;

3, Test regular expression test

test() regular object method, which is used to detect whether the string conforms to the rule.

<script>
    var regexp = new RegExp(/123/);  // true as long as 123 is included
    console.log(regexp.test(123));  // true
    console.log(regexp.test('abc'));  // false
</script>

4, Composition of regular expressions

A regular expression can consist of simple characters, such as / abc/
It can also be a combination of simple and special characters, such as / ab*c /
Special characters, also known as metacharacters, are special symbols with special significance in regular expressions.

Special characters

^: matches the text at the beginning of the line (starting with who)
$: matches the text at the end of the line (with whom)

<script>
    var regexp = new RegExp(/^123/);  // Indicates that it starts with 123
    console.log(regexp.test(1234));  // true
    console.log(regexp.test(1123));  // false
</script>
<script>
    var regexp = new RegExp(/123$/);  // Indicates that it ends with 123
    console.log(regexp.test(1234));  // false
    console.log(regexp.test(1123));  // true
</script>
<script>
    var regexp = new RegExp(/^123$/);  // It must be 123, but nothing else
    console.log(regexp.test(123));  // true
    console.log(regexp.test(1123));  // false
</script>

5, Character class

[] indicates that there are a series of characters to choose from, and only one of them can be matched.

<script>
    var regexp = new RegExp(/[123]/);  // Just match one of them
    console.log(regexp.test(1456));  // true
    console.log(regexp.test(246));  // true
</script>
<script>
    var regexp = new RegExp(/^[123]$/);  // Indicates that only one of a, b and c is true
    console.log(regexp.test(123));  // false
    console.log(regexp.test(2));  // true
</script>

[-]: square bracket range character-

<script>
    var regexp = new RegExp(/[a-z]/);  // Represents any character between a-z
    console.log(regexp.test('a'));  // true
    console.log(regexp.test('z'));  // true
</script>

^ in [] means negative

<script>
    var regexp = new RegExp(/[^a-z]/);  // The ^ in [] means negative
    console.log(regexp.test('a'));  // false
    console.log(regexp.test(1));  // true
</script>

6, Quantifier

*: repeat zero or more times
+: repeat one or more times
?: Repeat zero or once
{n} : repeat n times
{n,}: repeat n or more times
{n, m}: repeat n to m times

<script>
    var regexp = new RegExp(/^[a-z]{6}$/);  // {} indicates how many times the preceding character is repeated
    console.log(regexp.test('aaaaaa'));  // true
    console.log(regexp.test('a'));  // flase
</script>

Exercise: user name detection

<body>
    <input type="text"><span>enter one user name</span>
    <script>
        // regular expression 
        var regexp = new RegExp(/^[a-zA-Z0-9_-]{3,6}$/);  // {} indicates how many times the preceding character is repeated
        // Get element
        var input = document.querySelector('input');
        var span = document.querySelector('span');
        input.addEventListener("blur", function () {
            if (regexp.test(input.value)) {
                span.style.color = 'green';
                span.innerHTML = "The user name is legal";
            } else {
                span.style.color = 'red';
                span.innerHTML = "Illegal user name";
            }
        });
    </script>
</body>

7, Predefined classes

Predefined classes are shorthand for some common patterns

\d: Match any number between 0-9, equivalent to [0-9]
\D: Match any character except 0-9, equivalent to [^ 0-9]
\w: Match any letters, numbers and underscores, equivalent to [A-Za-z0-9_]
\W: Match any character except letters, numbers and underscores, equivalent to [^ A-Za-z0-9_]
\s: Match spaces (line breaks, tabs, spaces, etc.), equivalent to [\ t\r\n\v\f]
\S: Match any character except space, equivalent to [^ \ t\r\n\v\f]

8, Regular substitution

The replace() method can implement the replace string operation, and the parameter used to replace can be a string or a regular expression

stringObject.replace(regexp/substr, replacement)

Regular expression parameters

**/Expression / [switch]**

There are three kinds of values for the pattern of switch matching.
g: global matching
i: Ignore case
gi: global match, ignoring case

<script>
    var text = 'Passionate, Passionate';
    var text1 = text.replace(/passion/, '**');
    console.log(text1);  // **Full of passion
    var text2 = text.replace(/passion/g, '**');
    console.log(text2);  // **Four shot, * * four shot
</script>

Keywords: Javascript

Added by Gordonator on Mon, 17 Jan 2022 19:47:22 +0200