In practice ,JavaScript Regular expressions are often used . So this part of knowledge is very important .

One 、 Basic grammar :

The first one is : Literal grammar

var expression=/pattern/flags;

The second kind :RegExp Constructor Syntax

var pattern = /\w/gi; // Literal grammar 
var pattern = new RegExp('\\w', 'gi');// Constructor Syntax , The two are equivalent

Here's a caveat : If regular expressions are dynamic , You can only choose the second .

Among them flags Yes 3 A sign

g: Represent global mode , That is, the pattern will be applied to all strings , Instead of stopping immediately when the first match is found ;

i: Indicates case insensitive mode , That is, ignore the case of pattern and string when determining the match ;

m: For multiline mode , That is, when you reach the end of a line of text, you will continue to find whether there is an item matching the pattern in the next line .

Of course, there are other flags, Very little is used , Don't elaborate too much .

As for the above \w What do you mean , wait a moment , Please read on .

Two 、 Method

There are mainly test(),search(),match(),replace(). Of course, there are many other ways , No elaboration , After all, it's rarely used .

1、test() Use of methods

Determine whether a string contains the corresponding string

2、search() Use of methods

Search the index position where the corresponding string first appears , If not found , Then return to -1

3、match() Use of methods

Return matching array

4、replace() Use of methods , This is very much used

Match the corresponding string , Then replace it with another string

3、 ... and 、 Matching expressions with actual combat

1、 Assertion :

The so-called assertion , It means that a match occurs under certain conditions . In a word? , It's a bit of a concept , Look directly at the following . I'll take my time .

character describe
^ Match the beginning
$ Match the end
\b Match the boundaries of words
\B Match non word boundaries

for instance

I want to match a string , From the beginning to the end is dog, Ignore case

var pattern = /^dog$/i;// Ignore case
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;// The global matching , there +, It's a quantifier , representative 1 Times or more
console.log('Hello World'.match(pattern));// Output ['Hello','World'], Here is the match usage , Return matching array .

ad locum , Under the said ,\b It's the boundary of matching words , that \B It's matching the boundaries of non words . A lowercase , A capital , Capital is antonym . Then I don't have to say more .

Let's talk about word boundaries , Maybe a lot of people don't know the word boundaries very well



Let me explain a little bit , for instance ,Hello World There are four word boundaries , Namely H Location ,o Location ,W Location ,d Location

2、 Character class :

Metacharacters describe
. Find single character , Except for line breaks and line terminators
\w Find word characters , amount to [A-Za-z0-9_]
\W Find non word characters , amount to [^A-Za-z0-9_]
The following antonyms are no longer listed .
\d Find number , amount to [0-9]
\s Look for blank characters
\0 lookup NULL character
\n Find line breaks
\f Look for page breaks
\r Find the carriage return
\t Look for tabs
\v Find vertical tabs

3、 Range :

character describe
[abc] matching a,b,c Any character in
[^abc] Matching is not a,b,c Any character in
[0-9] matching 0-9 Any range of numbers , Empathy [a-z] matching a-z Any range of characters
[a-z] matching a To z Any character between
x|y matching x perhaps y

4、 quantifiers :

character describe
n+ Match anything that contains at least one character n String
n* Match any containing zero or more n String
n? Match anything that contains zero or one n String
n{x} Matching inclusion x individual n String
n{x,y} Match the least x individual , most y individual n String

Four 、 expand

matching 10-36 Number between

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

take 'Hello,World!Hello' Medium Hello Replace with Welcome

Here is to emphasize replace Methods used in regularization , Because this is very much used in practice . hinder flags Medium g, There is a big difference between adding and not adding .

var pattern = /Hello/g;
var oldString = 'Hello,World!Hello';
var newString = oldString.replace(pattern, 'Welcome');
console.log(newString);//Welcome,World!Welcome

Detailed explanation JavaScript More articles on regular expressions in

  1. 【 turn 】 Detailed explanation JavaScript Medium this

    ref:http://blog.jobbole.com/39305/ source :foocoder Detailed explanation JavaScript Medium this JavaScript Medium this It's always confusing , Should be js Well known pits ...

  2. Detailed explanation javascript in offsetleft Property usage ( turn )

    Detailed explanation javascript in offsetleft Property usage Reprint   2015-11-11   contribute :mrr     I want to comment on In this chapter, we will introduce offsetleft Property usage , A friend in need can be a ...

  3. Detailed explanation javascript Medium this object

    Detailed explanation javascript Medium this object Preface Javascript It's an object-based dynamic language , in other words , All things are objects , A typical example is that functions are also treated as ordinary objects .Javascript Can pass certain ...

  4. ( Reprint ) Detailed explanation Javascript in prototype attribute ( recommend )

    In a typical object-oriented language , Such as java, There are classes (class) The concept of , A class is a template for an object , An object is an instance of a class . But in Javascript In the language system , There is no class (Class) The concept of ,javascript Medium not ...

  5. Detailed explanation Javascript The use of regular expressions in

    Regular expressions are particularly useful for dealing with strings , stay JavaScript There are many things you can use regular expressions in , In this paper, the basic knowledge of regular expressions and Javascript Make a summary of the use of regular expressions in . The first part simply lists regular expressions in Ja ...

  6. 【 turn 】 Detailed explanation JavaScript Exception handling methods in

    There are three types of programming errors :(1) Grammatical errors and (2) Runtime error (3) Logic error : Grammar mistakes : Grammar mistakes , Also known as parsing errors , Traditional programming languages at compile time , And appear in JavaScript When interpreting . for example , The next line will lead to a ...

  7. Detailed explanation JavaScript Medium Event Loop( The event loop ) Mechanism

    Preface We all know ,javascript Since its birth, it is a single thread non blocking scripting language . This is determined by its original use : Interact with browsers . Single thread means ,javascript Code at any time of execution , There is only one main thread ...

  8. Detailed explanation JavaScript Medium arc Methods

    Today, let's talk about JavaScript The function to draw a circle in a web page arc! One .arc Required parameter settings 1 arc(x, y, radius, startAngle, endAngle, counterclockwise ...

  9. Detailed explanation JavaScript Medium Url code / decode , URL code in form submission

    This paper mainly aims at URI The related problems of encoding and decoding are introduced , Yes Url Which characters need to be encoded in encoding . Why coding is needed is explained in detail , And a comparative analysis of Javascript  neutralization Several pairs of functions related to encoding and decoding escape / unescape ...

  10. Detailed explanation JavaScript Medium this

    JavaScript Medium this It's always confusing , Should be js One of the well-known pits . I also feel that js Medium this Not a good design , because this Late binding features , It can be a global object , The current object , perhaps … Some people don't even know because of the big hole ...

Random recommendation

  1. Android Custom properties of custom control

    Preface : The first part introduces the basic requirements of custom control and the basic principle of drawing , This article mainly introduces how to customize some properties for custom controls . This article will continue to explain the custom circle percentage in the previous article . Please refer to Android Custom control ...

  2. .NET Alternative transformation path ( turn )

    a new year , In your study and work , I want to stick to what I have learned , Or try to transform ? (1) Continue to study C# 4.0 / AJAX / LINQ to AD.LINQ to JavaScript / WF, WCF, WPF, ...

  3. Eclipse Environment installation and configuration optimization

    1. Download the corresponding eclipse edition .    Official download address :http://www.eclipse.org/downloads/    juno Version of 64 Bit download address :http://www.eclipse.o ...

  4. Silent installation MSSQL

    Original address :http://www.cnblogs.com/lyhabc/p/3511788.html Introduce If you have 50 Servers need to be installed SQLSERVER, If you take the next step, the next step , Keep switching with remote desktop ...

  5. consul To eliminate node_exporter Script for

    #!/bin/bash clear echo "node_exporter Logout tool " read -p " Please enter the node to kick out IP, If there are more than one IP, Please use English format ',' Partition ...

  6. Oracle Study note 2

    Multi-table query : The cartesian product : It's actually the product of two tables , But it doesn't make much sense in actual development Format : select * from surface 1, surface 2 select * from emp; select * from dept; ...

  7. if(a)

    let a = undefined; let b = null; let c = ''; let d = ; let e = {}; let f = []; if (a) { console.log( ...

  8. Wechat applet swiper Use of front and back margins

    There is a component in the applet swiper  It's the slider view container Two properties are provided previous-margin: Front margin , Can be used to expose a small part of the previous item       next-margin: Back margin , Can be used to reveal the latter ...

  9. 1.shell Common sentences in learning

    This chapter studies content : 1. Common symbols 2. Command separator - A semicolon ";" 3. Double a semicolon ";;" 4. ' Single quotation marks and " Double quotes 5.` The quotes and $() 6.${} and $ 7. Risk ...

  10. Tag propagation algorithm (llgc or lgc)

    Hands on label propagation algorithm Repetition paper :Learning with Local and Global Consistency1 lgc The algorithm can be referred to :DecodePaper/notebook/lgc It's just ...