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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor