Learn more about using regular expressions in JavaScript

Learn more about using regular expressions in JavaScript

1. What is a regular expression

Is a pattern used to match character combinations in a string. In JavaScript, regular expressions are also objects.

Regular expressions are usually used to retrieve and replace text that matches a certain pattern (rule), such as in a validation form: the username form can only input English letters, numbers, or underscores, while the nickname input box can input Chinese characters (matching). In addition, regular expressions are often used to filter out some sensitive words in the page content (replacement), or to obtain the specific part we want from the string (extraction), etc.

1. Characteristics of regular expressions

Flexibility of regular expressions.

Very logical and functional.

Complex control of strings can be achieved quickly and in a very simple way.

2. Use of regular expressions

1. Create a regular expression

There are usually two ways to create it.

1) Create by calling the RegExp object's constructor

var variable name = new RegExp(/expression/); 

2) Create through literal

 var variable name = /expression/; 

// Putting an expression in the middle of a comment is a regular literal

2. Test regular expressions

test() Regular expression object method, used to detect whether a string conforms to the rule. The object returns true or false, and its parameter is the test string.

regexObj.test(str) 

in:

regexObj — regular expression to write

str — The text to test

This means checking whether the str text conforms to the written regular expression specification.

For example:

Given a regular expression var rg = /123/ , determine whether the string we input meets the rules.

var str = '123'
var reg1 = new RegExp(/123/);
var reg2 = /abc/;
console.log(reg1.test(str)); 
console.log(reg2.test(str));

The print result is;

2. Special characters in regular expressions

1. Composition of regular expressions

A regular expression can consist of simple characters, such as /abc/, or a combination of simple and special characters, such as /ab*c/. Special characters are also called metacharacters, which are special symbols with special meanings in regular expressions, such as ^, $, +, etc.

2. Boundary Characters

The boundary characters (position characters) in regular expressions are used to indicate the position of characters. There are mainly two characters.

Boundary Character illustrate
^ Matches text at the beginning of a line
$ Matches text at the end of a line

If ^ and $ are together, it means an exact match must be made.

3. Character Class

A character class indicates that there is a range of characters to choose from, and you only need to match one of them. All optional characters are enclosed in square brackets.

1. [] Square brackets

/[abc]/.test('andy') // true 

As long as the subsequent string contains any character in abc, true is returned.

2. [-] Range symbol inside square brackets -

/^[az]$/.test(c') // true

Adding - inside the square brackets indicates a range, here it means all 26 English letters from a to z are acceptable.

3. [^] Negation symbol inside square brackets ^

  /[^abc]/.test('andy') // false

Adding ^ inside the square brackets means negation. As long as the characters in the square brackets are included, false is returned.

Note the difference between ^ and the boundary character, which is written outside the square brackets.

4. Character combination

/[a-z1-9]/.test('andy') // true

Character combinations can be used inside the square brackets, which means that all 26 English letters from a to z and numbers from 1 to 9 are allowed.

4. Quantifier

Quantifiers are used to set the number of times a pattern occurs.

quantifier illustrate
* Repeat zero or more times
+ Repeat one or more times
? Repeat 0 or once
{n} Repeat n times
{n,} Repeat n times or more
{n,m} Repeat n to m times
var reg = /^a*$/; // * is equivalent to >=0, and can appear 0 times or many timesvar reg = /^a+$/; // + is equivalent to >=1, and can appear 1 time or many timesvar reg = /^a?$/; // ? is equivalent to 1||0, and can appear 0 times or 1 timevar reg = /^a{3}$/; // {3} means repeating character a 3 timesvar reg = /^a{3,}$/; // {3,} means repeating character a greater than or equal to 3 timesvar reg = /^a{3,16}$/; // {3,16} means repeating character a greater than or equal to 3 times and less than or equal to 16 times

For example, now let's do a username verification case. If the username input is legal, the prompt message is: the username is legal, and the color is green; if the username input is illegal, the prompt message is: the username is illegal, and the color is green.

The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="jquery.js"></script>
    <style>
        .success{
            color:green;
        }
        .wrong{
            color:red;
        }
    </style>
</head>
<body>
    Username:
        <input type="text" class="uname"><span></span>
    </label>
    <script>
       $(function(){
        var reg = /^[a-zA-Z0-9_-]{6,16}$/;
        $('.uname').bind('blur',function(){
            let str = $(this).val();
            if($('input').val === null){
                $('span').removeClass();
            }
            if(reg.test(str)){
                if($('span').hasClass('wrong'))
               $('span').removeClass()
                $('span').html('The input format is correct');
                $('span').addClass('success')
            }else{
                $('span').html('Input format error');
                $('span').addClass('wrong')
            }
        })
       })

    </script>
</body>
</html>

The display effect is:

5. Summary in brackets

Braces are used as quantifiers. They indicate the number of repetitions.

The set of bracket characters. Matches any character in the square brackets.

The parentheses indicate the priority

6. Predefined Classes

Predefined classes are shorthand for some common patterns.

3. Methods in the String class

1. match() method

match() method: matches all the content that meets the requirements according to the regular expression, and saves them into an array after a successful match. If the match fails, false is returned.

For example:

var str = "It's the shorthand of it is";
var reg1 = /it/gi;
str.match(reg1); // Matching result: (2) ["It", "it"]
var reg2 = /^it/gi;	
str.match(reg2); // Match result: ["It"]
var reg3 = /s/gi;	
str.match(reg3); // Matching results: (4) ["s", "s", "s", "s"]
var reg4 = /s$/gi;
str.match(reg4); // Matching result: ["s"]

2. search() method

search() method: The search() method can return the position where the substring of the specified pattern first appears in the string. It is more powerful than the indexOf() method.

For example:

var str = '123*abc.456';
console.log(str.search('.*')); // Output: 0
console.log(str.search(/[\.\*]/)); // Output: 3

3. split() method

split() method: The split() method is used to split a string into a string array according to the specified delimiter. The split string array does not include the delimiter.

For example:

The string is split according to the "@" and "." delimiters.

var str = '[email protected]';
var reg = /[@\.]/;
var split_res = str.split(reg);
console.log(split_res); // Output: (3) ["test", "123", "com"]

When splitting a string using regular expression matching, you can also specify the number of times the string is split.

var str = 'We are a family';
var reg = /\s/;
var split_res = str.split(reg, 2);
console.log(split_res); // Output: (2) ["We", "are"]

4. replace() method

replace() method: The replace() method is used to replace a string. The parameter used for the operation can be a string or a regular expression.

For example: Write a case to find and replace sensitive words (filter Chinese characters and the word 'bad'):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="display:flex">
    <div>
        <p>Content before filtering</p>
        <textarea name="" id="" cols="30" rows="10"></textarea>
        <button id = 'btn'>Filter</button>
    </div>
    <div>
        <p>Filtered content</p>
        <textarea name="" id="" cols="30" rows="10"></textarea>
    </div>
    <script>
        var text = document.querySelectorAll('textarea');
        console.log(text);
        var btn = document.querySelector('button');
        btn.onclick = function() {
            text[1].value = text[0].value.replace(/(bad)|[\u4e00-\u9fa5]/gi, '*');
        }
    </script>
</body>
</html>

The running effect is:

The above is the detailed content of in-depth understanding of the use of regular expressions in JavaScript. For more information about JavaScript regular expressions, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of JavaScript advanced regular expressions
  • Two ways of implementing interface association in jmeter (regular expression extractor and json extractor)
  • JavaScript Regular Expressions Explained
  • js implements the method of browsing local files and displaying extensions
  • JavaScript function to verify image type (extension)
  • JavaScript regular expression configuration extension and implementation verification

<<:  Simple example of HTML checkbox and radio style beautification

>>:  The difference between Div and table in HTML (discussed in detail in all aspects)

Recommend

Detailed explanation of the frame and rules attributes of the table in HTML

The frame and rules attributes of the table tag c...

Detailed explanation of Deepin using docker to install mysql database

Query the MySQL source first docker search mysql ...

JS implements the sample code of decimal conversion to hexadecimal

Preface When we write code, we occasionally encou...

A brief introduction to VUE uni-app core knowledge

Table of contents specification a. The page file ...

How to write beautiful HTML code

What Beautiful HTML Code Looks Like How to write ...

React implements infinite loop scrolling information

This article shares the specific code of react to...

MySQL trigger detailed explanation and simple example

MySQL trigger simple example grammar CREATE TRIGG...

CSS implements Google Material Design text input box style (recommended)

Hello everyone, today I want to share with you ho...

Discussion on Web Imitation and Plagiarism

A few months after entering the industry in 2005, ...

MySQL spatial data storage and functions

Table of contents 1. Data Type 1. What is MySQL s...

Detailed tutorial on using VMware WorkStation with Docker for Windows

Table of contents 1. Introduction 2. Install Dock...

Example of automatic stop effect after text scrolling

The effect is very simple, just copy the following...