当前位置:网站首页>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>边栏推荐
- Make a simple text logo with DW
- Sword finger offer 30 Stack containing min function
- How to improve data security by renting servers in Hong Kong
- QT tutorial: signal and slot mechanism
- Global and Chinese markets of lithium chloride 2022-2028: Research Report on technology, participants, trends, market size and share
- Meso tetra [P - (p-n-carbazole benzylidene imino)] phenylporphyrin (tcipp) /eu (tcipp) [pc( α- 2-oc8h17) 4] and euh (tcipp) [pc (a-2-oc8h17) 4] supplied by Qiyue
- Assign the CMD command execution result to a variable
- Virtual machine installation deepin system
- Day10 -- forced login, token refresh and JWT disable
- JMeter plug-in installation
猜你喜欢

IPv6 experiment

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

Upgrade PIP and install Libraries

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
![Meso tetra [P - (p-n-carbazole benzylidene imino)] phenylporphyrin (tcipp) /eu (tcipp) [pc( α- 2-oc8h17) 4] and euh (tcipp) [pc (a-2-oc8h17) 4] supplied by Qiyue](/img/5b/fc776a1982e24b82984d82be6a016f.jpg)
Meso tetra [P - (p-n-carbazole benzylidene imino)] phenylporphyrin (tcipp) /eu (tcipp) [pc( α- 2-oc8h17) 4] and euh (tcipp) [pc (a-2-oc8h17) 4] supplied by Qiyue

Xctf attack and defense world crypto master advanced area olddriver

Exercises of function recursion

Typora charges, WTF? Still need support

Wechat applet quick start (including NPM package use and mobx status management)

Detailed and not wordy. Share the win10 tutorial of computer reinstallation system
随机推荐
Camera calibration (I): robot hand eye calibration
Global and Chinese markets of cast iron diaphragm valves 2022-2028: Research Report on technology, participants, trends, market size and share
Upgrade PIP and install Libraries
Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
Part 27 supplement (27) buttons of QML basic elements
2. Template syntax
2022-06-28 advanced network engineering (XIII) IS-IS route filtering, route summary, authentication, factors affecting the establishment of Isis neighbor relations, other commands and characteristics
2.1 use of variables
4. Data splitting of Flink real-time project
Print linked list from end to end
FPGA learning notes: vivado 2019.1 project creation
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
Cap and base theory
February 14-20, 2022 (osgear source code debugging +ue4 video +ogremain source code transcription)
Teach you how to quickly recover data by deleting recycle bin files by mistake
Initialization and instantiation
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
unittest框架基本使用
Parental delegation mechanism