concept
How to create: Using a re requires creating regular expression objects, which can be created using constructors or literal methods
- Constructor:
New RegExp(" regular body ",[modifier])
- Literal:
/ regular body/modifier
methods
Method of regeting objects
test
Keyword, used to detect astring
Returns a value for compliance with certain rulestrue
andfalse
exec
Keyword to capture the first content that matches. Returns an array whose index is the position at which the first character of the match appears
// constructor
let reg = new RegExp("hello");
---------------------------------------------
/ / literal
let reg = /hello/g;
----------------------------------------------
let str = "hello,Javascript,Hello";
console.log(reg.exec(str));//
--------------------------------------------
console.log(reg.test(str));//true
Copy the code
String methods
// Template string
let str = "Lorem ipsum dolor sitip amet";
//match() captures the content of the string that matches the re. Returns NULL if the match fails
console.log(str.match(/am/g));// Result: ['am']
console.log(str.match(/id/g));// Result: null
// Note: the g modifier is a global match. If it is not added, only the first match will be matched
// replace() replaces the string
let arr = str.replace(/ip/g."id");
console.log(arr);Result (string) : Lorem idsum dolor sitid amet
// Search () finds the first occurrence of the string that matches the condition
let index = str.search("ip");
console.log(index);/ / results: 6
Copy the code
Metacharacters and qualified metacharacters
metacharacters
.
A wildcard character that matches a single arbitrary character[range]
Matches any of the ranges. Such as:[a-z]
[A-Z]
[0-9]
, pay attention to:[^ range]
Take the opposite meaning, for example:[^a-z]
, means that in addition toa-z
Any other characters of\d
Matching a single number equals[0-9]
,\D
Matches a single non-digit, equivalent to[^ 0-9]
\w
Matches a single number, letter, underscore equivalent[a-zA-Z0-9_]
;\W
Matches a single non-digit, non-letter, non-underscore equivalent[^a-zA-Z0-9_]
\s
Matches single whitespace character space newline (\ n), TAB (\t)\S
Matches a single non-whitespace character
Qualified metacharacter
Written after a regular metacharacter or alphabetic symbol to modify the number of occurrences of the preceding character
{m}
Indicates m occurrences. The equivalent of{m,m}
{m,}
There is no upper limit, minimum m matches.{m,n}
At least m times and at most N times.?
Is equivalent to{0, 1}
You either don’t show up, or you show up once.*
Is equivalent to, {0}
Matches any number of times (including zero).+
Is equivalent to{1,}
At least once.
Added: line start/line end qualifier
^
The beginning of the line must match the beginning of the following character$
End-of-line matches must end with the preceding character
var pattern = /^cha$/,
str = 'cha';
console.log(pattern.test(str));// Result: true
Copy the code
Greed and non-greed
- Greedy: When a string is matched with a re, it matches as many as possible. The re defaults to greedy.
- Non-greedy: When a string is matched with a regular, as many matches as possible are made, and qualifiers are written with one at the end
?
just
Regular expression online test tool:C.runoob.com/front-end/8…
case
Check input strength
- The password contains 8 to 12 characters
- Uppercase, lowercase, and strong.
- Weak if uppercase, lowercase, and number contain only one
- Everything else is medium
/ / CSS<style>
#box {
width: 224px;
display: flex;
justify-content: space-between;
}
#box span {
margin-top: 10px;
width: 60px;
height: 30px;
line-height: 30px;
text-align: center;
background-color: #ccc;
}
#box .active {
background-color: #f00;
}
</style>// HTML partial code:<input type="text" id="pwd"><br>
<div id="box">
<span>weak</span>
<span>In the</span>
<span>strong</span>
</div>
Copy the code
/ / js parts
const pwd = document.getElementById('pwd');
const spans = document.querySelectorAll("#box span")
pwd.onchange = function () {
// trim() clears Spaces
let str = pwd.value.trim();
if (/ ^ [a zA - Z0-9] {8, 12} $/.test(str)) {
// The length is suitable
if (/[A-Z]/.test(str) && /[a-z]/.test(str) && /\d/.test(str)) {
// The password strength is strong
clearOther();
spans[2].classList.add("active")}else if (/^[A-Z]+$/.test(str) || /^[a-z]+$/.test(str) || /^\d+$/.test(str)) {
// Password strength is weak
clearOther();
spans[0].classList.add("active")}else {
clearOther();
spans[1].classList.add("active")}}else {
alert("Passwords should be between 8 and 12 characters long.");
pwd.value = "";/ / to empty
pwd.focus(); // Get focus, re-enter}}function clearOther() {
for (var i = 0; i < spans.length; i++) {
spans[i].classList.remove("active"); }}Copy the code
Validates the date format entered
- Matching a date string is consistent with the rule: year-month-day
- 2021-12-01 (agreed) 2021-2-3 (agreed) 2021-2-03 (agreed) 2021/12/01 (not agreed) 2021-13-33 (not agreed)
- We are not considering leap years and leap months here
Input box: <input type="text" id="numstr"><br>
let numstr = document.getElementById("numstr")
numstr.onchange = function () {
let str = numstr.value.trim();
if (/^\d{4}-(0? [1-9] | [1] [2-0]) - (0? [1-9] | [1-2] [0-9] | [3] [0, 1]) $/.test(str)) {
alert("Meet")}else {
alert("No match")}}Copy the code
summary
- We used that when we were writing cases
(a|b)
Let’s call it branching. Let’s do a little example.
var regex = /^I love (JavaScript|Regular Expression)$/;
console.log( regex.test("I love JavaScript"));// => true
console.log( regex.test("I love Regular Expression"));// => true
Copy the code
- And we used it
(0? [1-9] | [1] [2-0])
For example, as scheduled: the first four digits of 2014, two digits of -December, and two digits of -28. Equivalent to grouping by bit.
Master these content we on JS re is the entry
Hahaha don’t ask who said 😂, ask is me