search
HomeWeb Front-endJS TutorialA concise summary of regular expressions in JavaScript_Basic knowledge

1. How to define regular expressions

There are two ways to define regular expressions: constructor definition and regular expression literal definition. For example:

Copy code The code is as follows:
var reg1 = new RegExp('d{5, 11} '); // Define
through constructor var reg2 = /d{5, 12}/; // Define
through direct quantity

Regular expression literal character
o: NUL character (u0000)
t: Tab character (u0009)
n: Line feed character (u000A)
v: Vertical tab character ( u000B)
f: Form feed character (u000C)
r: Carriage return character (u000D)
xnn: Latin character specified by the hexadecimal number nn. For example, x0A is equivalent to
uxxxx: Unicode character specified by hexadecimal number xxxx, for example, u0009 is equivalent to
🎜> ^: Matches the beginning of a string. In multi-line retrieval, matches the beginning of a line
$: Matches the end of a string. In multi-line retrieval, matches the end of a line
b: Matches a word The boundary, in short, is the position between the characters w and W, or the position between the character w and the beginning or end of the string ([b] matches the backspace character)
B: matches non- The position of the word boundary
(?=p): zero-width positive lookahead assertion, requiring the following characters to match p, but not including those characters that match p
(?!p): zero-width negative Assert to the lookahead, requiring that the following string does not match p
Regular expression character class
[...]: Any character within square brackets
[^...]: Not in square brackets Any character within brackets
.: Any character except newlines and other Unicode line terminators
w: Any word composed of ASCII characters, equivalent to [a-zA-Z0-9]
W: Any word that is not composed of ASCII characters, equivalent to [^a-zA-Z0-9]
s: Any Unicode whitespace character
S: Any non-Unicode whitespace character, pay attention to w and S Different
d: Any ASCII number, equivalent to [0-9]
D: Any character except ASCII digits, equivalent to [^0-9]
[b]: Backspace Direct quantity (special case)
Repeated character syntax of regular expression
{n, m}: Match the previous item at least n times, but not more than m times
{n, }: Match the previous item n times or more
{n}: Match the previous item n times
?: Match the previous item 0 or 1 times, which means the previous item is optional, equivalent to {0, 1}
: Matches the previous item 1 or more times, equivalent to {1, }
*: Matches the previous item 0 or more times, equivalent to {0, }
regular expression Selection, grouping and reference characters of expressions
|: Selection, matching the sub-expression on the left or the sub-expression on the right of the symbol
(...): Combination, combining several items into one unit, this Units can be modified by symbols such as "*", " ", "?" and "|", and the string matching this group can be remembered for any subsequent use
(?: ...): only Combination, combines items into one unit, but does not remember the characters that match the shuffling
n: Matches the first matching character of the nth group. The group is a subexpression in parentheses (it may also be Nested), the group index is the number of left brackets from left to right, grouping in the form of "(?:" is not encoded
Regular expression modifier
i: Perform case-insensitive matching
g: Perform a global match, in short, find all matches instead of stopping after finding the first one
m: Multi-line matching mode, ^ matches the beginning of a line and the beginning of a string, $ matches The end of the line and the end of the string
String method for pattern matching
search(): Its parameter is a regular expression, returning the starting position of the first matching substring. If If there is no matching substring, -1 is returned. If the parameter of search() is not a regular expression, it will first be converted to a regular expression through the RegExp constructor. search() does not support global retrieval because it ignores the modifier g. For example:


Copy code The code is as follows:

var s = "JavaScript".search(/script/i); // s = 4

replace(): It is used to perform retrieval and replacement. Receives two parameters, the first is the regular expression, and the second is the string to be replaced. If the modifier g is set in the regular expression, global replacement is performed, otherwise only the first matching substring is replaced. If the first argument is not a regular expression, the string is searched directly instead of being converted to a regular expression. For example:

Copy code The code is as follows:
var s = "JavaScript".replace(/java/gi , "Script"); // s = Script Script

Match(): Its parameter is a regular expression. If not, it is converted through RegExp and returns an array composed of matching results. If modifier g is set, a global match is performed. For example:

Copy code The code is as follows:
var d = '55 ff 33 hh 77 tt'.match (/d /g); // d = ["55", "33", "77"]

split(): This method is used to split the string that calls it into an array of substrings. The delimiter used is the parameter of split(), and its parameter can also be a regular expression. For example:

Copy code The code is as follows:
var d = '123,31,453,645'.split(', '); // d = ["123", "31", "453", "645"]
var d = '21, 123, 44, 64, 67, 3'.split(/s*, s*/); // d = ["21", "123", "44", "64", "67", "3"]

2. RegExp object
Each RegExp object has 5 attributes. The source attribute is a read-only string containing the text of the regular expression. The global attribute is a read-only Boolean value that indicates whether this regular expression has the modifier g. The attribute ignoreCase is a read-only Boolean value that indicates whether this regular expression has the modifier i. The multiline attribute is a read-only Boolean value that indicates whether this regular expression has the modifier m. The lastIndex attribute is a readable and writable integer. If the matching pattern has the g modifier, this attribute stores the starting position of the next search in the entire string.
The RegExp object has two methods. The parameter of exec() is a string, and its function is similar to match(). The exec() method executes a regular expression on a specified string, that is, performs a matching search in a string. If no match is found, null is returned. If a match is found, an array is returned. The first element of this array contains the string matching the regular expression, and the remaining elements are the subexpressions in parentheses. The matched substring, regardless of whether the regular expression has modifier g, will return the same array. When the regular expression object calling exec() has modifier g, it will set the lastIndex property of the current regular expression object to the character position immediately next to the matched substring. When exec() is called a second time with the same regular expression, it will start retrieving from the string indicated by the lastIndex attribute. If exec() does not find any matching results, it will reset lastIndex to 0. For example:

Copy code The code is as follows:
var p = /Java/g;
var text = "JavaScript is more fun than Java!"
var r;
while((r = p.exec(text)) != null) {
     console.log(r, 'lastIndex: ' p .lastIndex);
}

Another method is test(). Its parameter is a string. Use test() to check a certain string. If it contains a matching result of the regular expression, it will return true otherwise it will return false. For example:

Copy code The code is as follows:
var p = /java/i;
p. test('javascript'); // true
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 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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools