当前位置:网站首页>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)); // 5match
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-12The 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
gModifier uses the same regular when operated multiple times , That is to define regularity as a variable using - Use
gWhen 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>边栏推荐
- Realize user registration and login
- 2.6 formula calculation
- IP address is such an important knowledge that it's useless to listen to a younger student?
- 4. Data binding
- FPGA 学习笔记:Vivado 2019.1 工程创建
- 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
- Machine learning support vector machine SVM
- Day11 - my page, user information acquisition, modification and channel interface
- Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
- 2.4 conversion of different data types
猜你喜欢

44. Concurrent programming theory
![AI enhanced safety monitoring project [with detailed code]](/img/a9/cb93f349229e86cbb05ad196ae9553.jpg)
AI enhanced safety monitoring project [with detailed code]
![2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]](/img/b6/5d6b946d8001e2d73c2cadbdce72fc.png)
2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]

5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes

Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system

Exercises of function recursion

2.7 format output of values

IP address is such an important knowledge that it's useless to listen to a younger student?

2.5 conversion of different data types (2)

Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro
随机推荐
[effective Objective-C] - block and grand central distribution
Popularize the basics of IP routing
Network security Kali penetration learning how to get started with web penetration how to scan based on nmap
2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)
Day10 -- forced login, token refresh and JWT disable
MySQL learning notes - single table query
How to read the source code [debug and observe the source code]
PR 2021 quick start tutorial, material import and management
原生表格-滚动-合并功能
Micro service knowledge sorting - asynchronous communication technology
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
Basic command of IP address configuration ---ip V4
Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
Global and Chinese market of rubidium standard 2022-2028: Research Report on technology, participants, trends, market size and share
AI enhanced safety monitoring project [with detailed code]
Global and Chinese market of speed limiter 2022-2028: Research Report on technology, participants, trends, market size and share
First knowledge of database
11-grom-v2-05-initialization
10 smart contract developer tools that miss and lose
HCIA-USG Security Policy