Detailed explanation of the practical application of regular expressions in JavaScript

Detailed explanation of the practical application of regular expressions in JavaScript

In actual work, JavaScript regular expressions are still frequently used. So this part of knowledge is very important.

1. Basic grammar:

First: Literal syntax

var expression=/pattern/flags;

Second: RegExp constructor syntax

var pattern = /\w/gi; //literal syntax var pattern = new RegExp('\\w', 'gi'); //constructor syntax, these two are equivalent

One thing to note here is that if the regular expression is dynamic, only the second option can be selected.

The flags have 3 flags

g: indicates a global pattern, that is, the pattern will be applied to all strings instead of stopping immediately when the first match is found;

i: indicates a case-insensitive mode, that is, the case of the pattern and the string is ignored when determining the match;

m: Indicates multi-line mode, that is, when the end of a line of text is reached, the search continues to see if there is an item matching the pattern in the next line.

Of course there are other flags, but they are rarely used and will not be elaborated on in detail.

As for what the above \w means, wait a moment, please continue reading.

2. Methods

The main ones are test(), search(), match(), and replace(). Of course, there are many other methods, which I will not elaborate on here because they are rarely used.

1. Use of test() method

Determine whether a string contains a corresponding string

2. Use of search() method

Searches for the index of the first occurrence of the string, and returns -1 if not found.

3. Use of match() method

Returns an array of matches

4. The use of replace() method is still very common

Matches a string and replaces it with another string

3. Matching expressions and actual combat

1. Assertions:

An assertion indicates that a match occurs under certain conditions. In short, the concept is a bit confusing, so just read on. Let me continue slowly.

character describe
^ Matches the beginning
$ Matches the end
\b Matching word boundaries
\B Matches non-word boundaries

For example

I want to match a string that starts with dog and ends with dog, ignoring case.

var pattern = /^dog$/i; //Ignore uppercase and lowercase console.log(pattern.test('dog')); //true
console.log(pattern.test('sdfdog'));//false
console.log(pattern.test('dog56'));//false
console.log(pattern.test('dOG'));//true
var pattern = /\b\w+/g; //Global match, the + here is a quantifier, representing 1 or more times console.log('Hello World'.match(pattern)); //Output ['Hello','World'], this is the usage of match, returning an array of matches.

Here, \b matches the boundary of a word, and \B matches the boundary of a non-word. One lowercase and one uppercase, the uppercase ones are the opposite. Then I don’t need to say more.

Let's talk about word boundaries. Maybe many people are not very clear about word boundaries.

Let me explain it briefly. For example, the word Hello World has four boundaries, namely H position, o position, W position, and d position.

2. Character class:

Metacharacters describe
. Finds a single character, except newline and line terminator
\w Find word characters, equivalent to [A-Za-z0-9_]
\W Find non-word characters, equivalent to [^A-Za-z0-9_]
The antonyms below are no longer listed.
\d Search for a number, equivalent to [0-9]
\s Find whitespace characters
\0 Find NULL characters
\n Find line breaks
\f Find page breaks
\r Find carriage return
\t Find Tab Characters
\v Find vertical tab characters

3. Scope:

character describe
[abc] Matches any character in a, b, c
[^abc] Matches any character that is not a, b, or c
[0-9] Matches any number in the range 0-9. Similarly, [az] matches any character in the range az.
[az] Matches any character between a and z
x|y Matches x or y

4. Quantifiers:

character describe
n+ Matches any string containing at least one character n
n* Matches any string containing zero or more n
n? Matches any string containing zero or one n
n{x} Matches a string containing x n
n{x,y} Matches a string with at least x and at most y n characters

4. Expansion

Matches a number between 10 and 36

var pattern = /1[2-9]|[2-3][0-9]|4[0-6]/;//12-46

console.log(pattern.test(11));//false
console.log(pattern.test(12));//true
console.log(pattern.test(20));//true
console.log(pattern.test(36));//true
console.log(pattern.test(46));//true
console.log(pattern.test(47));//false

Replace Hello in 'Hello, World! Hello' with Welcome

Here we mainly emphasize the use of the replace method in regular expressions, because this is used very frequently in practice. There is a big difference between adding or not adding the g in the flags.

var pattern = /Hello/g;

var oldString = 'Hello,World!Hello';
var newString = oldString.replace(pattern, 'Welcome');
console.log(newString);//Welcome,World!Welcome

Summarize

This is the end of this article about the practical application of regular expressions in JavaScript. For more relevant JavaScript regular expressions, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on the application of common regular expressions in Javascript
  • The concept and application of regular expressions in JavaScript
  • Application of multiline attribute of JavaScript regular expression
  • JS application regular expression conversion example
  • js replace regular expression application case explanation
  • Detailed explanation of the application of regular expressions in Javascript

<<:  Detailed explanation on how to avoid the pitfalls of replacing logical SQL in MySQL

>>:  Linux debugging tools that developers and operators must look at [Recommended]

Recommend

Xftp download and installation tutorial (graphic tutorial)

If you want to transfer files between Windows and...

How to change the root password in a container using Docker

1. Use the following command to set the ssh passw...

How to control the proportion of Flex child elements on the main axis

background Flex layout achieves alignment and spa...

The difference between ${param} and #{param} in MySQL

The parameter passed by ${param} will be treated ...

How to install Oracle_11g using Docker

Install Oracle_11g with Docker 1. Pull the oracle...

express project file directory description and detailed function description

app.js: startup file, or entry file package.json:...

Detailed steps to install CentOS7 system on VMWare virtual machine

Pre-installation work: Make sure vmware workstati...

Solution to the MySQL error "Every derived table must have its own alias"

MySQL reports an error when executing multi-table...

How to create scheduled tasks using crond tool in Linux

Preface Crond is a scheduled execution tool under...

How to introduce img images into Vue pages

When we learn HTML, the image tag <img> int...

Docker nginx example method to deploy multiple projects

Prerequisites 1. Docker has been installed on the...

How to change the dot in the WeChat applet swiper-dot into a slider

Table of contents background Target Effect Ideas ...