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

mysql5.7.18 decompressed version to start mysql service

The decompressed version of mysql5.7.18 starts th...

Detailed explanation and extension of ref and reactive in Vue3

Table of contents 1. Ref and reactive 1. reactive...

Analysis of MySQL data backup and recovery implementation methods

This article uses examples to describe how to bac...

WeChat applet implements a simple calculator

A simple calculator written in WeChat applet for ...

Summary of how to add root permissions to users in Linux

1. Add a user . First, use the adduser command to...

Circular progress bar implemented with CSS

Achieve results Implementation Code html <div ...

Why do code standards require SQL statements not to have too many joins?

Free points Interviewer : Have you ever used Linu...

MySQL transaction control flow and ACID characteristics

Table of contents 1. ACID Characteristics Transac...

Detailed analysis of MySQL 8.0 memory consumption

Table of contents 1. innodb_buffer_pool_size 2. i...

A brief discussion on this.$store.state.xx.xx in Vue

Table of contents Vue this.$store.state.xx.xx Get...

MySQL json format data query operation

The default table name is base_data and the json ...

JavaScript imitates Xiaomi carousel effect

This article is a self-written imitation of the X...

How to create an index on a join table in MySQL

This article introduces how to create an index on...