JavaScript - regular expressions

Posted by chet23 on Mon, 25 Oct 2021 16:11:19 +0200

JavaScript advanced day 04 notes

0. Why use regular expressions*

For example: find a number in a string

		var str = '3s4 d5 f6gy uiml,./567y ghv/.,';
        var arr = [];

        var temp = '';
        for(var i = 0; i < str.length; i++){
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                temp += str.charAt(i);
                    arr.push[temp];  //Push numbers into arr
                    //temp is cleared and ready to receive the next number
                    temp = '';

If using regular:

var re = /\d+/g;

With regular, you can save a lot of code and effort

1. Regular expression overview

1.1 what is a regular expression

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 conforms to a certain pattern (rule), such as validation forms: the user name form can only enter English letters, numbers or underscores, and the nickname input box can enter Chinese (matching). In addition, regular expressions are often used to filter out some sensitive words in the page content (replacement), or get the specific part we want from the string (extraction), etc.

Other languages also use regular expressions. At this stage, we mainly use JavaScript regular expressions to complete form verification.

1.2 characteristics of regular expressions

  1. Flexibility, logic and functionality are very strong.
  2. It can quickly achieve the complex control of string in a very simple way.
  3. For people who have just come into contact, it is more obscure and difficult to understand. For example: ^ \ w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w +)*$
  4. In actual development, regular expressions are usually copied directly. However, regular expressions are required to be used and modified according to the actual situation. For example, user name:/ 1{3,16}$/

2. Use of regular expressions in js

2.1 creation of regular expressions

In JavaScript, you can create a regular expression in two ways.

Method 1: create by calling the constructor of RegExp object

var regexp = new RegExp(/123/);

Method 2: create regular expressions with literal values

 var rg = /123/;

2.2 testing regular expressions

The test() regular object method is used to detect whether the string conforms to the rule. The object will return true or false, and its parameter is the test string.

var rg = /123/;
console.log(rg.test(123));//Whether 123 appears in the matching character, and the result is true
console.log(rg.test('abc'));//Whether 123 appears in the matching character. If it does not appear, the result is false

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-6KW4WN5K-1630715686317)(images/img4.png)]

2.3 other regular functions can be used

2.3.1 use of search

Find a string that matches a regular pattern and find the location of the returned string

console.log(;   //Find 'g' return subscript
console.log(;    //Not found, return - 1

Example: determining browser type userAgent

var userA = window.navigator.userAgent;
if( != -1){
}else if( != -1){

2.3.2 match

Find the value that matches the regular expression and return an array

var rel = /\d\d/g;
var rel = /\d/g;

2.3.3 replace

Replace the regular expression

var str = 'bhnjkm,.cfvyike,';
re = /b|j/g;      //Filter b and j in str and replace with**
var str1 = str.replace(re, '**');

Example: sensitive word filtering

        var text = document.querySelectorAll('textarea');
        var btn = document.querySelector('button');
        btn.onclick = function(){
            //Get text information before filtering
            var str = text[0].value;
            var re = /juvenile|Mountains and rivers/g;
            var str1 = str.replace(re, '**');
            text[1].value = str1;

3. Special characters in regular expressions

3.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, also known as metacharacters, are special symbols with special significance in regular expressions, such as ^, $, + and so on.

There are many special characters. You can refer to:


jQuery Manual: regular expressions section

Regular test tool

3.2 boundary character

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

Boundary characterexplain
^Represents the text that matches the beginning of the line (starting with who)
$Represents the text that matches the end of the line (with whom)

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

        //Test test, return true on the matching, otherwise return false
        var rel = /^abc/;
        console.log(rel.test('abc'));   //true
        console.log(rel.test('cabc'));    //false
        console.log(rel.test('abcsf'));    //true

        //The beginning and the end must match
        var rel1 = /^abc$/;
        console.log(rel.test('abc'));    //true
        console.log(rel.test('cabc'));   //false
        console.log(rel.test('sabcsf'));   //false

3.3 character class

Character class means that there are a series of characters to choose from, as long as you match one of them. All selectable characters are placed in square brackets.

3.3.1 [] square brackets

Indicates that there are a series of characters to choose from, as long as you match one of them

		var str = /[abc]/;
        var str1 = /^[abc]/;
        var str2 = /^[abc]$/;
        console.log(str2.test('andy'));  //true t f
        console.log(str2.test('simon')); //false f f
        console.log(str2.test('fengzia')); //true f f

3.3.2 quantifier**

Quantifier is used to set the number of times a pattern appears.

*Repeat 0 or more times
+Repeat 1 or more times
?Repeat 0 or 1 times
{n}Repeat n times
{n,}Repeat n or more times
{n,m}Repeat n to m times

3.3.4 bracketed summary

1. The inside of the brace quantifier indicates the number of repetitions

2. The bracketed character set matches any character in the brackets

3. Parentheses indicate priority

Regular expression online test

3.4 predefined classes (escape characters)

Predefined classes are shorthand for some common patterns

  1. a-z0-9_- ↩︎

Topics: Javascript Front-end regex