当前位置:网站首页>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>边栏推荐
- Virtual machine installation deepin system
- 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
- Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
- Win10 share you don't have permission
- 10 smart contract developer tools that miss and lose
- Exercises of function recursion
- Plan for the first half of 2022 -- pass the PMP Exam
- Use of aggregate functions
- 11-grom-v2-05-initialization
- 2.5 conversion of different data types (2)
猜你喜欢

1.5 learn to find mistakes first

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

Virtual machine installation deepin system

It is discussed that the success of Vit lies not in attention. Shiftvit uses the precision of swing transformer to outperform the speed of RESNET

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

FPGA 学习笔记:Vivado 2019.1 工程创建

FPGA learning notes: vivado 2019.1 project creation

Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper

BOC protected amino acid porphyrins TAPP ala BOC, TAPP Phe BOC, TAPP Trp BOC, Zn · TAPP ala BOC, Zn · TAPP Phe BOC, Zn · TAPP Trp BOC Qiyue

Commands related to files and directories
随机推荐
Day11 - my page, user information acquisition, modification and channel interface
Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
Test changes in Devops mode -- learning and thinking
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
How can the outside world get values when using nodejs to link MySQL
原生表格-滚动-合并功能
Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
Explore the internal mechanism of modern browsers (I) (original translation)
FPGA 学习笔记:Vivado 2019.1 工程创建
2.4 conversion of different data types
Point cloud data denoising
Today's work summary and plan: February 14, 2022
1.5 learn to find mistakes first
Global and Chinese market of micro positioning technology 2022-2028: Research Report on technology, participants, trends, market size and share
Implementation of stack
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
IP address is such an important knowledge that it's useless to listen to a younger student?
Test access criteria
Assign the CMD command execution result to a variable
Popularize the basics of IP routing