search
HomeWeb Front-endJS TutorialRegular expressions in JavaScript

First of all, what is a regular expression?

Regular expression is an expression of custom rules, used to match strings that match the defined rules. What's the meaning? For example, this is a regular expression: /d/, d means any number, so the meaning of this regular expression is to match any number. You probably understand it!

Let’s take a look at what regular expressions consist of.

1. Direct character

Regular expressions in JavaScript

2. Range class

Regular expressions in JavaScript

What does it mean? For example: /[a-z]3{1,3}5+/ This expression means that any English letter appears once, then the number 3 appears one to three times, and then the number 5 appears at least once.

Let’s try it using the test() method in the chrome debugging tool:

Note: The test() method is used to check whether a string matches a certain regular expression and receives a parameter, which is the target string. If it matches Then return true, otherwise return false

Regular expressions in JavaScript

3. Character class

Regular expressions in JavaScript

What is this, the baby can’t understand it! Let's look at an example: /[abc]wd{2}/, this expression means, match any one of abc, followed by a word ([a-zA-Z0-9]) or an underscore, then Two numbers. Look at the picture!

Regular expressions in JavaScript

4. Anchor character

Regular expressions in JavaScript

Let’s talk about ^ here, which means it starts with... Let’s look at an example:

Regular expressions in JavaScript

For comparison, there is no ^

Regular expressions in JavaScript

$ in the expression here The principle is the same as ^, so I won’t go into details here. Just note that $ needs to be written at the end of the expression.

5. Modifiers

Regular expressions in JavaScript

Without the g modifier, the regular expression stops matching when it matches the first item. When there is the g modifier, all matching items will be found. We learn a new method of regular expression, replace():

Note: The replace() method is used to replace the specified characters in the string and receives two parameters. The first parameter is a regular expression, indicating that you want to replace The second parameter is a string indicating the content you want to replace. See the example below!

Regular expressions in JavaScript

Only the first number has been replaced. Let’s look at the situation with the g modifier:

Regular expressions in JavaScript

All the numbers have been replaced. Now you understand what g is for.

Let’s talk about i. The i modifier is very simple, indicating that it is not case-sensitive. See the following example:

Regular expressions in JavaScript

After adding i, all uppercase and lowercase letters are replaced!

The last m represents multi-line search. For example, if you want to match a string starting with the letter a, if there is the m modifier, the lines starting with a after line breaks will also be matched. Due to space limitations, no pictures are included here.

6. Grouping

Using parentheses () in regular expressions represents grouping, and each () represents a grouping. The content in the group is represented by $1, $2..., still look at the example:

For example, dates have these two representations: month-day-year and year/month/day, how to change month-day-year into year What about /month/day? Let’s take a look at

Regular expressions in JavaScript

In this example, we group the month, day and year, and then use $backreference to achieve date format conversion.

7. Methods

Now that I’ve basically finished talking about the bits and pieces of regular expressions, let’s start learning the methods used in regular expressions! There are two categories, one is the regular expression object method, and the other is the string object method.

1. There are two regular expression object methods

, test() and exec(). We have learned the test() method, now let’s talk about the exec() method. The

exec() method returns an array. The first element of the array is the matched text, the second element is the first sub-text of the matched text, and the third element is the second sub-text of the matched text... And so on. This is very abstract, just look at the example below to understand!

Exec() calls are divided into two situations: non-global calls and global calls.

Non-global call situation:

Look at the example below

Regular expressions in JavaScript

Here we see that "a12b" is matched for the first time, and the next two elements are the first group "1" and the second group. "2". But when the exec() method is executed for the second time, the match is still "a12b", which is unexpected. It stands to reason that the second match should be "c56d", but why is it still "a12b"? The reason lies in the lastIndex attribute. The lastIndex attribute represents the next character of the last character of the last matching result, but this attribute only takes effect when called globally (that is, when the g modifier is added to the expression), and is always 0 when called non-globally. For comparison, let's take a look at the global call situation!

Global call situation:

Regular expressions in JavaScript

You can see that the first execution of exec() returns "a12b", and lastIndex is 4, which is the position of number 3 in the string str; the second time it returns "c56d" ", lastIndex is 10, which is the position of the number 7 in the string str. At this time lastIndex takes effect, so the results of the two executions are as expected.

2. String object methods

String object methods include: search(), replace(), match(), split().

1. Search() method

The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. If a match is found, the index of the first matching result is returned. If no match is found, -1 is returned. Receives a parameter, which can be a string or a regular expression. This method starts matching from the beginning of the string every time. Let’s look at the following example:

Regular expressions in JavaScript

The index returned by searching for the number 2 twice is 1, not the index 5 of the second number 2. The third and fourth searches passed in a regular expression and both returned the corresponding index.

2. replace() method

This method has been learned before, so continue here. There are several forms: replace(str,replaceStr), replace(RegExp,replaceStr), replace(RegExp,function). The first two are relatively simple, just look at an example to understand:

Regular expressions in JavaScript

The first time you pass in a string, replace the number 2 with X, the second time you pass in a regular expression, replace all the numbers with X. The second parameter of the

replace(RegExp,function) method is a function. This method is suitable for more complex character replacement. If you are interested, you can find learning resources by yourself. I will not introduce it here.

3. Match() method

The match() method passes in a parameter: a regular expression, which is used to find the text in the string that matches the passed regular expression. If it is not found, it returns null. If Find and return an array. This array is different between non-global calls and global calls, which will be discussed separately below.

Non-global call:

When called non-globally, the returned array is like this: the first element is the matched text, the second element is the first sub-text of the matched text, and the third element is the matched The second subtext of the text... and so on. Does it feel like déjà vu? Yes, this is exactly the same as the exec() method.

Regular expressions in JavaScript

When calling non-globally, each search still starts from the beginning of the string. Let’s take a look at the global call!

Global call:

When called globally (that is, there is a g modifier in the regular expression), the returned array is like this: each item in the array is the matching text, and there is no longer a sub-text of the matching text. .

Regular expressions in JavaScript

"a12b" and "c56d" that match the regular expression appear in the array. In fact, the match() method and the exec() method have the same function, except that one is called by a string and the other is called by a regular expression.

4. split() method

The split() method is used to split a string into an array. What does it mean? Look at the following example: The parameter received by the

Regular expressions in JavaScript

split() method can be a string or a regular expression. As you can see from the example, whatever parameters are passed are removed from the string and then split into arrays.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.