search
HomeWeb Front-endJS TutorialA summary of the usage of common regular expressions in js

This article brings you a summary of the usage of regular expressions commonly used in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I have done several projects recently and found that regular expressions are used more and more. My personal habit is not to memorize things that can be obtained by looking up manuals. Although most technical websites have collected a bunch of usage of Javascript regular expressions, I still want to compile a manual with more practical significance. To put it bluntly, if you need to use regular expressions in the future, just come over and copy and paste them! I will try my best to make the layout as beautiful as possible so that everyone can improve development efficiency. The preceding is a concise usage of Javascript regular expressions. Please skip to the last section for practical content.

Three modifiers

There are three modifiers in Javascript's regular expressions: i, g, m

After adding i, regular matching is no longer case-sensitive (Default case-sensitive):

var reg = /j/;
reg.test('Javascript'); //结果为false
var reg2 = /j/i;
reg2.test('Javascript'); //结果为true

javascript

After adding g, global matching will be performed (default will stop after matching once):

var reg = /a/;
'Javascript'.replace(reg,'e'); //结果为Jevascript
var reg2 = /a/g;
'Javascript'.replace(reg2,'e'); //结果为Jevescript

javascript

After adding m, multi-line matching will be performed (only one line by default):

var reg = /^s/;
reg.test('Java\nscript'); //结果为false
var reg2 = /^s/m;
reg2.test('Java\nscript'); //结果为true

javascript

Methods involving regular expressions

Many people may be confused about the functions used by regular expressions. Here are some commonly used methods:

The string is followed by 3 common functions: match(reg) (returns the matched string) , replace(reg,'...') (replace content), search(reg) (return the starting position of the matching content)

The regular expression is followed by 2 common functions: test(string) (return Whether it matches), exec(string) (returns the matched string)

Declaration of regular expressions

There are two declaration methods, use them according to the specific situation:

var reg = /a/; // 普通声明方式,大多数情况下使用
var reg2 = new RegExp('a','g'); // 字符串声明方式,部分情况特别有用

JS regular expression practical usage

JS regular expression for mailbox:

var mailReg = /^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

JS regular expression for mobile phone:

var phoneReg = /^1\d{10}$/;

JS regular expression for ID card:

var idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

JS regular expression for name (Chinese characters):

var nameReg = /^[\u4e00-\u9fa5]{2,4}$/; // 2-4位的汉字名字

JS regular expression for common domain name:

var urlReg = /^(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*([\?&]\w+=\w*)*$/; // https或http协议的url

JS regular expression for username:

var userNameReg = /^[A-Za-z0-9-_]*$/; // 用户名为数字英文下划线或短划线

JS regular expression for QQ number:

var qqReg = /^[1-9][0-9]{4,}$/;

JS regular expression for zip code:

var mailReg = /^[1-9][0-9]{5}$/;

JS regular expression for HTML tag:

var tagReg = /<[^>]+>/; //可以用来去掉html文本中的标签,得到纯文字

JS for date Regular expression:

var dateReg = /^\d{4}-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]\d|3[0-1])$/; //YYYY-MM-dd格式,短线可以视情况替换

JS regular expression of time:

var timeReg = /^([0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/; //HH:mm:ss格式,冒号可以视情况替换

The above are some commonly used JS regular expressions

Related recommendations:

How does js format xml string and highlight it? (Attached code)

JS basic series of regular expressions

The above is the detailed content of A summary of the usage of common regular expressions in js. For more information, please follow other related articles on the PHP Chinese website!

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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function