当前位置:网站首页>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>边栏推荐
- Promethus
- Analysis of gas fee setting under eip1559
- Global and Chinese market of rubidium standard 2022-2028: Research Report on technology, participants, trends, market size and share
- Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
- Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
- How to check the permission to write to a directory or file- How do you check for permissions to write to a directory or file?
- Make a simple text logo with DW
- Day10 -- forced login, token refresh and JWT disable
- Kubernetes cluster builds efk log collection platform
- Use of aggregate functions
猜你喜欢

Upgrade PIP and install Libraries

Commands related to files and directories

Phpstudy set LAN access
![2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]](/img/b6/5d6b946d8001e2d73c2cadbdce72fc.png)
2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]

2.6 formula calculation

BOC protected phenylalanine zinc porphyrin (Zn · TAPP Phe BOC) / iron porphyrin (Fe · TAPP Phe BOC) / nickel porphyrin (Ni · TAPP Phe BOC) / manganese porphyrin (Mn · TAPP Phe BOC) Qiyue Keke
![AI enhanced safety monitoring project [with detailed code]](/img/a9/cb93f349229e86cbb05ad196ae9553.jpg)
AI enhanced safety monitoring project [with detailed code]
![[effective Objective-C] - block and grand central distribution](/img/09/22b979b97ea13d649b4b904637b79f.jpg)
[effective Objective-C] - block and grand central distribution

2.1 use of variables

JMeter plug-in installation
随机推荐
2022-06-30 網工進階(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
Upgrade PIP and install Libraries
Wechat applet quick start (including NPM package use and mobx status management)
Camera calibration (I): robot hand eye calibration
Geek Daily: the system of monitoring employees' turnover intention has been deeply convinced off the shelves; The meta universe app of wechat and QQ was actively removed from the shelves; IntelliJ pla
4. Data binding
unittest框架基本使用
Find a line in a file and remove it
Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
Battle drag method 1: moderately optimistic, build self-confidence (1)
Exercises of function recursion
unittest框架基本使用
7. Data broker presentation
How to read the source code [debug and observe the source code]
11-grom-v2-04-advanced query
Global and Chinese markets of polyimide tubes for electronics 2022-2028: Research Report on technology, participants, trends, market size and share
MPLS configuration
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue