current position:Home>Dry goods | regular application (actual combat summary)
Dry goods | regular application (actual combat summary)
2021-08-27 10:07:06 【Weibo front end】
See everyone playing Nuggets I also github Copy and send an article If useful Support a lot
Regular applications ( summary )
1. Common business examples
Common business ( user name , Password strength, etc , There is no list of , Search a lot .), You can also see what I summarized 《 Regular expressions commonly used in front-end form validation 》
1.1 User name regular
// User name regular ,4 To 16 position ( Letter , Numbers , Underline , minus sign )
var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
// Output true
console.log(uPattern.test("caibaojian"));
// The strength of the password must be a combination of upper and lower case letters and numbers , Special characters cannot be used , The length is in 8-10 Between .
var reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z]{8,10}$/;
Copy code
2. Regular grouping
Regular expressions are character by character to match , So if you want to match a word, such as
is
, Just have to write/is/
, If you want to matchis
appear 3 Time , You can only write /isisis/
, We want to use quantifiers/is{3}/
, But this only meanss
appear 3 Time , How can I modify it to expressis
Three times , holdis
Enclosed in brackets ,/(is){3}/
. Put... In parenthesesis
Cover up , It means that it is a whole , A group , They will appear together , It's a successful match , So it's called grouping . Grouping has an important concept , It's quoting , When there are groups in a regular expression , We can get the content of the group , How to get , Namely$n
,n
Representation number ,$1
Represents the content of the first group ,$2
Represents the content of the second group ,$3
Represents the content of the third group , By analogy , In fact, there is another$0
, It's more special , So list it separately , It said , The entire regular expression matches the successful content
2.1 Example ( If the telephone number is hidden in the middle )
// Example 1
var reg=/(\d{3})\d{4}(\d{4})/;
var phone="13423874592";
console.log( phone.replace(reg,("$1****$2")));//134****4592
// Example 2: The hump changes into a middle line
'fooBarBaz'.replace(/([A-Z])/g,"-$1").toLowerCase() // foo-bar-baz
// Example 3
let reg = /(\d{4})-(\d{2})-(\d{2})/g;
let string = '2017-03-20'
let replaceString = string.replace(reg,"$2/$3/$1");
console.log(replaceString) // 03/20/2017
// Example 4
let reg = /(\d)2\1/g;
let string = '121 222 323 424'
let replaceString = string.replace(reg,'X');
console.log(replaceString) // X X X X
Copy code
3. Add variables
// http://blog.csdn.net/icanlove/article/details/39499777
var v = "bl";
var re =new RegExp("^\d+" + v + "$","gim"); // re by /^\d+bl$/gim
// thus , The original problem has been completely solved .
// in addition , Another way is to use eval A method of dynamically executing a string , But I think from all aspects , It's all bad policy .
var re = eval("/^\d+" + v + "$/gim")
Copy code
4. string Of replace
Find a regular string , Just replace it with the corresponding string . Return the content after replacement
usage : String.replace( Regular , New string / Callback function )
( In the callback function , The first parameter refers to the characters that match successfully every time )
Example : Sensitive word filtering , such as ” I love tian 'anmen square in Beijing , The sun rises over tian 'anmen square “.------ I love *****,*** The sun rose on the . namely ( Beijing and Tiananmen become Number ),
At first we might think of such a method :
var str = " I love tian 'anmen square in Beijing , The sun rises over tian 'anmen square .";
var re = / Beijing | The tiananmen square /g; // Find Beijing Or tiananmen square The global matching
var str2 = str.replace(re,'*');
alert(str2) // I love **,* The sun rose on the
// This just turns what you find into a *, Not just a few words *.
Copy code
If you want to realize that a few words correspond to several *, We can use callback function to realize :
var str = " I love tian 'anmen square in Beijing , The sun rises over tian 'anmen square .";
var re = / Beijing | The tiananmen square /g; // Find Beijing Or tiananmen square The global matching
var str2 = str.replace(re,function(str){
console.log(str); // For testing : The first parameter of the function represents the regular characters found each time , So the first time str I mean Beijing The second time str Is the tiananmen square third time str Is the tiananmen square
var result = '';
for(var i=0;i<str.length;i ){
result = '*';
}
return result; // So when you find a few words, you return a few *
});
console.log(str2) // I love *****,*** The sun rose on the
Copy code
The whole process is , Find Beijing , Replaced with two *, Find Tiananmen Square and replace it with 3 individual *, Find Tiananmen Square and replace with 3 individual *.
var arr = {
content: " Hello #D12345#,hello#D321#world",
lawitems: {
"D12345": "aaaa",
"D321": "bbbbb"
}
}
arr.content = arr.content.replace(/#([^#]+)#/g, function (match, $1) {
return arr.lawitems[$1]||match;// Not in the lawitems Find and return the original string
})
// " Hello aaaa,hellobbbbbworld"
Copy code
replace
Is a very useful method , Often used .
5. Boundary class (boudary)
The boundary class mainly uses four : ^ To begin with ,$ What does it end with , boudary Show word boundaries ,B Indicates a non word boundary . The boundary is where words are separated from words , The most obvious is the space .
Writing an example can be more intuitive .
let reg = /is/g;
let string = 'this is a dog '
let replaceString = string.replace(reg,"IS");
console.log(replaceString) // thIS IS a dog
Copy code
Two is
All replaced , This is in line with expectations . But how can we just replace the middle is
, In the middle of the is
There is a feature , It's a word , Because there are spaces in front and behind , Makes it separate from other words , Because there are spaces is
To become a word , So spaces are word boundaries , \b
Can match it . Change the regular expression to /\bis/g
, You can see the output this IS a dog
, Only match the second . What if you just want to change the first one ? That's good to do , Because the first one is Contained in a word , So it's not preceded by a word boundary , Direct change to B
That's all right. , Change the regular expression to /Bis/g
That's all right. .
Hump turn -
const hyphenateRE = /\B([A-Z])/g
const str = 'LiuWeiBo'
str.replace(hyphenateRE, '-$1').toLowerCase() // liu-wei-bo
Copy code
6. Regular assertion
Assertion , Match only one location , For example, look at the following example
// such as , You want to match a “ people ” word , But you just want to match the Chinese characters , People who don't want to match the French can use the expression
/(?<= China ) people /
// therefore , Expressions can only work when used in conjunction with other wildcards .
/(?=.*[a-z])\d/
// This is just saying Match with “ Any character followed by a lowercase letter ” Number at the beginning , Match only numbers .
Copy code
// Example 1
String(123456789).replace(/(\d)(?=(\d{3})+$)/g, "$1,");
// or
'123456789'.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
// The result is :123,456,789
// Example 2: Integers and decimals are compatible
'1234567890030.7890'.replace(/(?=\B(?:\d{3})+\b)(\d{3}(.\d+$)?)/g,',$1');
Copy code
6.1 (?=pattern)
Forward assertion
Represents a position in a string , The character sequence immediately after this position can match
pattern
For example a regular expression
This string , To match regular
Medium re, But can't match expression
Medium re
, It can be used re(?=gular)
, The expression qualifies re
On the right , This position is followed by gular
, But it doesn't consume gular
These characters , Change the expression to re(?=gular).
, Will match reg
, Metacharacters . Match the g
, The weight of brackets matches e and g
Position between .
6.2 (?!pattern)
Negative antecedent assertion ( Negative pre check , Non-fetch match )
Represents a position in a string , The character sequence immediately after this position cannot match
pattern
For example regex represents regular expression
This string , To match, divide regex
and regular
In addition to the re, It can be used re(?!g)
, The expression qualifies re
On the right , This position is not followed by a character g
. The difference between negative and positive , It depends on whether the character after this position can match the expression in parentheses .
// Will not match to contain df The content of
var reg = /^(?!.*df).*$/ // df It's a string you don't want to match .
reg.test('[email protected]') // true
var str = `[email protected] [email protected] [email protected] [email protected]`
reg.test(str) // false
Copy code
6.3 (?<=pattern)
Forward and backward assertions
Represents a position in a string , The character sequence immediately before this position can match
pattern
ES6+ Support post assertion
For example regex represents regular expression
This string , Yes 4 Word , To match the inside of a word re
, But it doesn't match the beginning of the word re
, It can be used (?<=\w)re
, Inside the word re
, stay re
It should be preceded by a word character . That's why it's called late assertion , Because the regular expression engine matches strings and expressions , Is to scan the characters in the string one by one from the front to the back , And judge whether it conforms to the expression , When the assertion is encountered in an expression , The regular expression engine needs to detect the scanned characters at the front of the string , It is backward relative to the scanning direction .
6.4 (?<!pattern)
Negative hindrow assertion
Represents a position in a string , The character sequence immediately preceding this position cannot match
pattern
. ES6+ Support post assertion
For example regex represents regular expression
This string , To match the beginning of a word re
, It can be used (?<!\w)re
. At the beginning of the word re
, In this case , That is, not inside the word re
, namely re
Not preceded by word characters . You can also use it \bre
To match .
7. Multi-line matching
^
and $
Well understood. , /^T/
In capital letters T
At the beginning , /T$/
In capital letters T
At the end , Pay attention to their writing position , One in front of , One in the back . If there is a newline character in the string , let string = '@123 @456 @789'
, The string behaves as if it had three lines . Here are chrome
Output in browser
At this time, if /^@/g
To match , It will only match the first @,
let reg = /^@/g;
let string = `@123 @456 @789`
let replaceString = string.replace(reg,"X");
console.log(replaceString)
/* * X123 * @456 * @789 */
Copy code
If you want to match three , Then you need to use m
Modifier , Multiline identifier , It means that if there is a newline character in the string , Think of strings as multiple lines .m
Identifier , Only in regular expressions ^ or &
It works when , This is also the handle. m
The reason why the identifier is put here .
More dry goods and high-quality articles move forward : weibozzz.github.io/
copyright notice
author[Weibo front end],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827100658897c.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich