当前位置:网站首页>Instructions for common methods of regular expressions
Instructions for common methods of regular expressions
2022-07-03 20:13:00 【GMLGDJ】
String method
search
search() Method to retrieve the substring specified in the string , You can also use regular expressions to search , The return value is the index position
let str = "baidu.com";
// String search
console.log(str.search("com")); // 6
// Regular search
console.log(str.search(/\.com/i)); // 5
match
Simple search string
let str = "baidu.com";
// String search
console.log(str.match("coma"));
// Use regular search
console.log(str.match(/com/));
// Return results If there is no match, return null
// {
// 0: "com", // Matching results
// groups: undefined, // Atomic group
// index: 6, // Position of appearance
// input: "baidu.com", // Queried characters
// }
If you use g
When it comes to embellishments , There will be no details of the results ( have access to exec or matchAll), Here's how to get all h1~6 The title element of
<body>
<h1>111</h1>
<h2>222</h2>
<h3>333</h3>
<script>
let body = document.body.innerHTML;
let result = body.match(/<(h[1-6])>[\s\S]+?<\/\1>/g);
// Return results ['<h1>111</h1>', '<h2>222</h2>', '<h3>333</h3>']
console.log(result);
</script>
</body>
matchAll
Support the use of matchAll operation , And return the iteration object .
const str = "baidu.com";
const reg = /[a-z]/ig;
const arr = []
for (const iterator of str.matchAll(reg)) {
console.log(iterator);
arr.push({
...iterator
})
}
/**
* return RegExpStringIterator object
* Need to use for of Take the corresponding value
* The data structure of each item ['u', index: 4, input: 'houdunren', groups: undefined] ( And match similar )
*/
console.log(str.matchAll(reg));
console.log(arr);
split
Used to separate strings using strings or regular expressions
// Use a string to separate dates
let str1 = "2023-02-12";
console.log(str1.split("-")); //["2023", "02", "12"]
// If the connector of the date is uncertain , Then use regular operation
let str2 = "2023/02-12";
console.log(str2.split(/-|\//)); //["2023", "02", "12"]
replace
replace Method can not only perform basic character replacement , Regular substitution is also possible , Now replace the date connector
let str = "2023/02/12";
console.log(str.replace(/\//g, "-")); //2023-02-12
The replacement string can be inserted into the following special variable name :
Variable | explain |
---|---|
$$ | Insert a "$". |
$& | Insert matching substring . |
$` | Insert the content to the left of the current matching substring . |
$' | Insert the content to the right of the current matching substring . |
$n | $n For the first time n Content matched by atomic groups . Tips : The index is from 1 Start |
stay yq Add corresponding content before and after
let yq = "11yq==";
console.log(yq.replace(/yq/g, " $$ $` $& $' $$ "));
Use the telephone number -
Connect
let phone = "(010)99999999 (020)8888888";
console.log(phone.replace(/\((\d{3,4})\)(\d{7,8})/g, "$1-$2"));
replace Support callback function operation , For dealing with complex replacement logic
Variable name | Value represented |
---|---|
match | Matching substring .( Corresponding to the above $&.) |
p1,p2, ... | If replace() The first parameter of the method is a RegExp object , It stands for the third n String with brackets matching .( Corresponding to the above $1,$2 etc. .) for example , If it is to use /(\a+)(\b+)/ This to match ,p1 It's a match \a+ ,p2 It's a match \b+ . |
offset | The offset of the matched substring in the original string .( such as , If the original string is 'abcd' , The substring matched is 'bc' , So this parameter will be 1) |
string | The original string being matched . |
NamedCaptureGroup | Name the objects that the capture group matches |
Add hot
class
<body>
<div class="content">
<h1> Baidu </h1>
<h2>baidu.com</h2>
<h1> Baidu </h1>
</div>
<script>
let content = document.querySelector(".content");
let reg = /<(h[1-6])>([\s\S]*?)<\/\1>/gi;
content.innerHTML = content.innerHTML.replace(
reg,
(
search, // Matched characters
p1, // The first atomic group
p2, // The second atomic group
index, // Index position
source // Original character
) => {
return `
<${p1} class="hot">${p2}</${p1}>
`;
}
);
console.log(content.innerHTML);
</script>
</body>
The regular way
test
return true or false, The following is a case to check whether the entered email is legal
<body>
<input type="text" name="email" />
<script>
let email = document.querySelector(`[name="email"]`);
email.addEventListener("keyup", e => {
console.log(/^\[email protected]\w+\.\w+$/.test(e.target.value));
});
</script>
</body>
exec
Don't use g
Modifier with match
The method is similar , Use g
After the modifier, it can be called circularly until all matches are completed .
- Use
g
Modifier uses the same regular when operated multiple times , That is to define regularity as a variable using - Use
g
When the modifier does not match at last, it returnsnull
In the calculation content a Number of occurrences
<body>
<div class="content">
abababab
</div>
<script>
let content = document.querySelector(".content");
let reg = /a/g;
let num = 0;
while ((result = reg.exec(content.innerHTML))) {
num++;
}
console.log(result = reg.exec(content.innerHTML))
console.log(`a appear ${num} Time `);
</script>
</body>
边栏推荐
- Global and Chinese markets of cast iron diaphragm valves 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
- 【leetcode】1027. Longest arithmetic sequence (dynamic programming)
- [Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
- CMD implements the language conversion of locale non Unicode programs
- 5. MVVM model
- Day11 - my page, user information acquisition, modification and channel interface
- First knowledge of database
- unittest框架基本使用
- BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
猜你喜欢
BOC protected alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC supplied by Qiyu
Acquisition and transmission of parameters in automatic testing of JMeter interface
Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro
Commands related to files and directories
Xctf attack and defense world crypto advanced area best_ rsa
Virtual machine installation deepin system
Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
FPGA learning notes: vivado 2019.1 project creation
How to read the source code [debug and observe the source code]
2022 Xinjiang latest road transportation safety officer simulation examination questions and answers
随机推荐
Upgrade PIP and install Libraries
【c】 Digital bomb
2.5 conversion of different data types (2)
Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
5. MVVM model
2.4 conversion of different data types
BOC protected tryptophan porphyrin compound (TAPP Trp BOC) Pink Solid 162.8mg supply - Qiyue supply
Battle drag method 1: moderately optimistic, build self-confidence (1)
6. Data agent object Defineproperty method
BOC protected tryptophan zinc porphyrin (Zn · TAPP Trp BOC) / copper porphyrin (Cu · TAPP Trp BOC) / cobalt porphyrin (cobalt · TAPP Trp BOC) / iron porphyrin (Fe · TAPP Trp BOC) / Qiyue supply
Native table - scroll - merge function
WPF format datetime in TextBlock- WPF format DateTime in TextBlock?
2022-06-30 網工進階(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
10 smart contract developer tools that miss and lose
Machine learning support vector machine SVM
Win10 share you don't have permission
Pat grade B 1009 is ironic (20 points)
FAQs for datawhale learning!
Fingerprint password lock based on Hal Library
Print linked list from end to end