Here comes the brain map for this article
1. Regular knowledge
1.1 What is Re
❝
Regular expression:RegExp (a rule for processing strings)
❞
- Used to“Handling strings“Can only handle strings, not strings can’t be handled, but can be used
toString()
Method to string, ha ha ha, is not wrapped, the following example to understand. - It is a “rule” : it can verify that a string conforms to a rule (test), and it can capture the content of a string that conforms to the rule (exec/match…).
1.2 Preliminary view of re
❝
Here’s an example of using a re to validate a string! Take a quick look at the format, and if you’re new to regex, you should be able to understand this example by the end of the article.
❞
let str = 'good';
let reg = /\d+/;
reg.test(str); //false
str = '2020-04-09';
reg.test(str); //true
Copy the code
2. Write regular expressions
2.1 Creation Mode
2.1.1 Literal creation method
The metacharacters used to describe the rules are wrapped between two diagonal bars
let reg1 = /\d+/;
Copy the code
2.1.2 Constructor schema creation
Write it as a string, using the regular object new
Let reg2 = new RegExp('\\d+');Copy the code
❝
Either way, the result is of the object data type. Although reg1 and reg2 have the same rules, reg1! ==reg2, they have different heap memory addresses. (This involves the knowledge of JS data types, do not understand the small partners can go to review yo!)
❞
2.2 Composition of regular expressions
Is very important,“Memorize it, memorize it, memorize it…“This is the basis of re, and if you don’t understand what each character represents, re is basically useless
2.2.1 metacharacters
- Quantifier metacharacter: Sets the number of occurrences
metacharacters | meaning |
---|---|
* | Zero to many times |
+ | One or several times |
? | Zero to one |
{n} | N time |
{n,} | N to many times |
{n,m} | N to m times |
- Special metacharacters: individual or combined to represent a special meaning
metacharacters | meaning |
---|---|
\ | Escape character |
. | Any character except \n (newline character) |
^ | Which metacharacter to start with |
$ | Which metacharacter to end with |
\n | A newline |
\d | A number between 0 and 9 (including 0 and 9) |
\D | Divided by a number between 0 and 9 |
\w | Any character contained in digits, letters, and underscores |
\s | A whitespace character (including Spaces, tabs, and page feeds) |
\t | One TAB (one TAB key, four Spaces) |
\b | Matches the boundaries of a word |
x|y | A character in x or y |
[xyz] | A character in x or Y or Z |
[^xy] | Any character other than x and y |
[a-z] | Specifies any character in the a-z range |
[^a-z] | Take the opposite of the last one. |
(a) | A grouping symbol in a re |
(? 🙂 | Match only, no capture |
(? =) | Positive study |
(? !). | Reverse study |
-
Common metacharacter: representing its own meaning
/name/
This re is to match in a string'name'
2.2.2 Modifiers: Placed outside the regular expression/j/g
The modifier | meaning |
---|---|
i(ignoreCase) | Ignore case matching |
m(multiline) | Multiple line matching is possible |
g(global) | The global matching |
u(Unicode) | Used to correctly handle Unicode characters greater than \uFFF |
y(sticky) | adhesion |
s(dotAll) | Make ‘.’ match any character, including \n\r |
Memorize it, memorize it, memorize it
2.3 Common metacharacters
2.3.1 ^ $
❝
When we write regular expressions, we usually add these two metacharacters and write our rules between them for more rigor. {n, m} will be used in conjunction with it.
❞
- ^ What metacharacter to start with
- What metacharacter ends $
- ^/$The string contains the content that matches the rule
- ^/$The string must be consistent with the rule
// Matches a string that starts with a number
let reg = /^\d/;
console.log(reg.test('name')); //false
console.log(reg.test('2020name')); //true
console.log(reg.test('name2020')); //false
Copy the code
// Matches a string that ends with a number
let reg = /\d$/;
console.log(reg.test('name')); //false
console.log(reg.test('2020name')); //false
console.log(reg.test('name2020')); //true
Copy the code
// ^/$
let reg1 = /\d/;
console.log(reg1.test('as2')); //true
//^/$
let reg2 = /^\d$/
console.log(reg2.test('as2')); //false
console.log(reg2.test('22')); //false
console.log(reg2.test('2')); //true
Copy the code
2.3.2 \
- Escape characters, which can turn meaningless to meaningful, and meaningful to meaningless.
// '. 'represents any character other than a newline, not a decimal point
let reg = 2.3 $/ / ^;
console.log(reg.test('2.3')); //true
console.log(reg.test('2 @ 3')); //true
console.log(reg.test('23')); //false
// Now we change the '. 'to a normal decimal point.
let reg = $/ / ^ 2 \. 3;
console.log(reg.test('2.3')); //true
console.log(reg.test('2 @ 3')); //false
Copy the code
2.3.3 x | y
- X or y: direct x | y will priority problems, usually used with the brackets grouping, because parentheses change processing priority = > parentheses: grouping
// It matches a string that starts with 18 or ends with 29, starts with 1 and ends with 9, 8 or 2
// All of the following matches are true
let reg = 18 | $29 / / ^;
console.log(reg.test('18'));
console.log(reg.test('and'));
console.log(reg.test('129'));
console.log(reg.test('189'));
console.log(reg.test('1829'));
console.log(reg.test('182'));
// There are many ways to understand the above without parentheses, but if we use parentheses, it is impossible to understand the above;
// Matches one of 18 or 29, the rest are false
let reg = $/ / ^ 18 | (29);
console.log(reg.test('18'));
console.log(reg.test('and'));
console.log(reg.test('129'));
console.log(reg.test('189'));
Copy the code
2.3.4 []
- The character “generally” in parentheses stands for its own meaning (degaussing it, eliminating its own meaning)
- \d in parentheses still means 0-9, which is not demagnetized
- [18] : represents either 1 or 8
- [10-29] : represents either 1 or 9 or 0-2
// The decimal point is the same as the decimal point
let reg = + $/ / ^ [.];
Copy the code
// Match can only be @ or +
let reg = / ^ @ + $/;
console.log(reg.test(The '@')); //true
console.log(reg.test('+')); //true
console.log(reg.test('@ @')); //false
console.log(reg.test('@ +')); //false
Copy the code
// match meaning: \d still stands for 0-9
let reg = /^[\d]$/;
console.log(reg.test('9')); //true
console.log(reg.test('\ \')); //false
console.log(reg.test('d')); //false
Copy the code
// Matching means either 1 or 8
let reg = $/ / ^ [18];
console.log(reg.test('1')); //true
console.log(reg.test('8')); //true
console.log(reg.test('18')); //false
Copy the code
// Match meaning: 1 or 0-2 or 9
let reg = $/ / ^ [10-29];
// Match meaning: 1 or 0-2 or 9 or '(' or ')'
let reg = / ^ $/ / (10-29);
Copy the code
2.3.5 {n, m}
- It is n to m occurrences of the preceding metacharacter
❝
The example below, do not add ^ $although beyond the scope of the returned is true, but at the time of using the exec capture, capture the most four (the problem is when I was studying in one of the biggest struggle, if you don’t know and begin ending operator, has been called the {n, m} is beyond the range is no matter use, ha ha)
❞
// This regex matches two to four occurrences of a number. The third regex should return false, but the result is true
let reg = / / \ d {2, 4};
reg.test('1'); //false
reg.test('14'); //true
reg.test('123456'); //true
// Add ^$to the string. If the string contains only two or four digits, then the string contains only two or four digits. // Add ^$to the string
let reg = / ^ \ d {2, 4} $/;
reg.test('1'); //false
reg.test('14'); //true
reg.test('123456'); //false
Copy the code
2.3.6 Grouping Functions
- 1. Change the default priority.
- 2. Group capture;
- 3. Group references
// The first function is to increase priority. Reg1 can match more matches than reg2. This function has been mentioned above, so I will not write in detail here
let reg1 = 18 | $29 / / ^;
let reg2 = $/ / ^ 18 | (29)
Copy the code
// Second effect: when using exec to capture not only the results of the entire large re, but also the results of each group separately
let reg1 =/^([1-9]\d{5})((19|20)\d{2})(0[1-9]|10|11|12)(0[1-9]|[1-2]\d|30|31)\d{3}(\d|x)$/i;
Copy the code
// The third function: the first is the letter a-z, group 1; The second letter is also a-Z, group 2; The third place \2 is exactly the same as the second group...
let reg1 =/^([a-z])([a-z]\2\1)$/
Copy the code
2.3.7 Group Nomenclature (Naming groups)? < name >
let str = '132123201203200000';
let reg = / ^ (? [1-9]\d{5})(? (19|20)\d{2})(?
0[1-9]|10|11|12)(?
0[1-9]|[1-2]\d|30|31)\d{3}(\d|x)$/i
;
let res = reg.exec(str);
console.log(res);
console.log(res.groups.B);// You can get the contents of group B directly
Copy the code
2.3.8 Five functions of question mark in regularization
- 1. The left side of the question mark is a non-quantifier metacharacter.
- 2. To the left of the question mark are quantifier metacharacters: ungrabby;
-
- (? 🙂 : only match but not capture;
- 4. (? =) : forward pre-check;
-
- (? !). Negative lessons
2.4 Common regular expressions
2.4.1 Verifying the Mobile phone number
Rules:
- 11
- The first is the number 1
- The second digit is any one of the numbers 3-9
let reg = /^1[3-9]\d{9}$/;
console.log(reg.test('13245678945')); //true
console.log(reg.test('1324567895')); //false
console.log(reg.test('12245678945')); //false
Copy the code
2.4.2 Verifying whether it is a valid digit
Rules:
- You can start with a plus minus
- Integer:
- It could be anything from 0 to 9 if it’s a single digit;
- If it’s a multi-digit number, it can’t start with a 0;
- Decimal place: If there is a decimal place, there is at least one digit after it, or there may be no decimal place
let reg = / ^ (+ -)? (\d|[1-9]\d+)(\.\d+)? $/;
console.log(reg.test('0.2')); //true
console.log(reg.test('02.1')); //false
console.log(reg.test('20.)); //false
Copy the code
2.4.3 Verifying passwords
Rules:
- 6-16 is
- Must be alphanumeric
let reg = / ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]) [\ d (a-z) (a-z)] 6 16th} {$/;
Copy the code
2.4.4 Verifying the real name
Rules:
- It has to be Chinese characters
- The name is 2-10 characters in length
- Possible translation: · Chinese characters
Add: how to hit the middle point: in Chinese state, the key below ESC can be used
let reg = / ^ [\ u4E00 - \ u9FA5] {2, 10} (· [\ u4E00 - \ u9FA5] {2, 10})? $/;
Copy the code
2.4.5 Verifying email Addresses
Rules:
- Email name with ‘alphanumeric underline -.’ a few parts, but – /. Can continuously appear nor as beginning \ w + ((\ w +) | (. \ w +)) *.
- @ can be followed by alphanumeric, can appear multiple @[A-zA-Z0-9]+;
- Additions to @ names: multi-domain com.cn; Corporate domain (. | -) [A Za – z0-9] +) *
- Domain names such as.com/.cn.[A-za-z0-9]+
let reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
Copy the code
2.4.6 Verifying id number
Rules:
- 18
- The last digit is a number or an X
- The top six are provinces and counties
- The last four are years
- The last two are Month 01-12
- The last two are 01-31
- The last four
- Last digit: X or number
- Penultimate second: even: female: odd: male Function of bracketing group: group capture, not only can capture the large regular matching information, but also can capture the content of each small group separately
let reg =/^([1-9]\d{5})((19|20)\d{2})(0[1-9]|10|11|12)(0[1-9]|[1-2]\d|30|31)\d{3}(\d|x)$/i;
Copy the code
2.5 Using re to write the verification of the registration page
2.5.1 layout
I used bootstrap layout (ahem, we only need to be a senior CV engineer for this one, hahaha)
- Download the bootstrap package under the project file. You can download the bootstrap package directly from the official website or run commands to download the bootstrap package in the Node environment
npm i bootstrap
- Import the CSS from the package you just downloaded into the page
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
- Go to the bootstrap website to find the structure you need and copy it to your own page.
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<style>
.container {
padding: 0;
width: 300px;
}
.form-text {
color: red ! important;
}
</style>
</head>
<body>
<section class="container">
<form>
<div class="form-group">
<label>Real name</label>
<input type="text" class="form-control" id='userNameInp'>
<small class="form-text text-muted" id='userNameTip'></small>
</div>
<div class="form-group">
<label>email</label>
<input type="email" class="form-control" id='userEmailInp'>
<small class="form-text text-muted" id='userEmailTip'></small>
</div>
<div class="form-group">
<label>The phone</label>
<input type="text" class="form-control" id='userPhoneInp'>
<small class="form-text text-muted" id='userPhoneTip'></small>
</div>
<div class="form-group">
<label>password</label>
<input type="password" class="form-control" id='userPassInp'>
<small class="form-text text-muted" id='userPassTip'></small>
</div>
<div class="form-group">
<label>Confirm password</label>
<input type="password" class="form-control" id='userPassConfirmInp'>
<small class="form-text text-muted" id='userPassConfirmTip'></small>
</div>
<button type="button" class="btn btn-primary" id='submit'>submit</button>
</form>
</section>
</body>
</html>
Copy the code
2.5.2 JS validation
- All fields must be filled in;
- Input format must meet requirements;
- Verify when the mouse mouse leaves the text box;
- Check when you click the submit button;
let reginModule = (function () {
let query = function (selector) {
return document.querySelector(selector);
}
let userNameInp = query('#userNameInp'),
userNameTip = query('#userNameTip'),
userEmailInp = query('#userEmailInp'),
userEmailTip = query('#userEmailTip'),
userPhoneInp = query('#userPhoneInp'),
userPhoneTip = query('#userPhoneTip'),
userPassInp = query('#userPassInp'),
userPassTip = query('#userPassTip'),
userPassConfirmInp = query('#userPassConfirmInp'),
userPassConfirmTip = query('#userPassConfirmTip'),
submit = query('#submit');
// Name validation Trim () removes Spaces at the beginning and end of the string
let checkName = function checkName() {
let val = userNameInp.value.trim(),
reg = / ^ [\ u4E00 - \ u9FA5] {2, 10} (· [\ u4E00 - \ u9FA5] {2, 10})? $/;
if (val.length === 0) {
userNameTip.innerHTML = 'Real name cannot be empty';
return false;
}
if(! reg.test(val)) {
userNameTip.innerHTML = 'Not in name format';
return false;
}
userNameTip.innerHTML = ' ';
return true;
};
//EMAIL
let checkEmail = function checkEmail() {
let val = userEmailInp.value.trim(),
reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if (val.length === 0) {
userEmailTip.innerHTML = 'Mailbox cannot be empty';
return false;
}
if(! reg.test(val)) {
userEmailTip.innerHTML = 'Email format is not correct';
return false;
}
userEmailTip.innerHTML = ' ';
return true;
};
/ / cell phone number
let checkPhone = function checkPhone() {
let val = userPhoneInp.value.trim(),
reg = /^1[3-9]\d{9}$/;
if (val.length === 0) {
userPhoneTip.innerHTML = 'Mobile phone number cannot be empty';
return false;
}
if(! reg.test(val)) {
userPhoneTip.innerHTML = 'Mobile phone number format is not correct';
return false;
}
userPhoneTip.innerHTML = ' ';
return true;
};
/ / password
let checkPass = function checkPass() {
let val = userPassInp.value.trim(),
reg = / ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]) [\ d (a-z) (a-z)] 6 16th} {$/;
if (val.length === 0) {
userPassTip.innerHTML = 'Password cannot be empty';
return false;
}
if(! reg.test(val)) {
userPassTip.innerHTML = 'Incorrect password format';
return false;
}
userPassTip.innerHTML = ' ';
return true;
};
// Confirm the password
let checkPassC = function checkPassC() {
let val = userPassConfirmInp.value.trim(),
val2 = userPassInp.value.trim();
if(val ! == val2) {
userPassConfirmTip.innerHTML = 'Inconsistent passwords';
return false;
}
userPassConfirmTip.innerHTML = ' ';
return true;
};
/ / submit
let handel = function handel() {
if(! checkName() || ! checkEmail() || ! checkPass() || ! checkPassC() || ! checkPhone()) {
return;
}
alert('Please go to login');
}
return {
init() {
userNameInp.onblur = checkName;
userEmailInp.onblur = checkEmail;
userPhoneInp.onblur = checkPhone;
userPassInp.onblur = checkPass;
userPassConfirmInp.onblur = checkPassC;
submit.onclick = handel;
}
};
}) ();
reginModule.init();
Copy the code
2.5.3 effect
3. Re capture
In order to achieve the capture of the re, first need to match with the re (test method is true, can capture).
- regular
RegExp.prototype
Methods on (exec, test) - string
String.prototype
Support regular expression processing methods on replace, match, splite…
3.1 EXEC (Method on regular Prototype)
❝
The acquisition of regex based on exec has two properties: lazy and greedy. Therefore, there is a saying that people should not be too ‘regular’ ha ha ha
❞
3.1.1 Laziness: Only one is captured by default
- The result of capture is
null
Or an array- Item 1: the contents captured this time
- Other items: contents of this single loop corresponding to small groups
index
: The starting index of the current captured content in the stringinput
: Raw string
- Each time
exec
, can only catch one match of the regex rule, but by default, we execute a hundred times, and the result is always the first match, and the rest are not caught
let str = 'name2020name2020name2020';
reg =/\d+/;
console.log(reg.exec(str));//["2020", index: 4, input: "name2020name2020name2020", groups: undefined]
Copy the code
3.1.2 Lazy solutions
reg.lastIndex
: indicates the starting index position of the next match of the current re
let str = 'name2020name2020name2020';
reg =/\d+/;
console.log(reg.lastIndex);/ / 0
Copy the code
“Reason:” By default, the value of lastIndex is not changed. It is always looked up from the beginning of the string, so it always finds the first one. So you can solve this problem by simply changing lastIndex. “Solution:” Set the global modifier g
❝
When the global modifier g is set, the value of lastIndex changes itself after the first match. When all are captured, the result of the next capture is null, but the lastIndex is returned to the original value of zero, and the next capture starts from the first one again… LastIndex is also modified after validation based on test matches
❞
3.1.3 Encapsulate the solution to regular laziness
Requirement: Write a method execAll that can be executed once to capture the results of all matches (the global qualifier g must be set before the re is executed)
~ function(){
function execAll(str = ' '){
if(!this.global) return this.exec(str);
let ary = [],
res = this.exec(str);
while(res){
ary.push(res[0]);
res = this.exec(str);
}
return ary.length ===0?null:ary;
}
RegExp.prototype.execAll = execAll;
} ();
let reg = /\d+/g.
str = 'name2020name2020';
console.log(reg.execAll(str));
Copy the code
3.1.4 TanLanXing
By default, the longest result matched by the current re is retrieved.
let str = 'name2020'.
reg = /\d+/g;
console.log(str.match(reg));
Copy the code
3.1.5 Solve the problem of cupidity of re
Set after the quantifier metacharacter? Uncupidity at capture (obtained as the shortest result of regular matching)
let str = 'name2020'.
reg = /\d+? /g;
console.log(str.match(reg));
Copy the code
3.2 regular packet capture () | string match method
Analyze the results of the following chestnuts:
- The first item: the result of the grand re match
- Remaining items: Each small group individually matches the captured results
- If you set grouping (change priority), but do not need to capture separately, can be based on? : to process without capturing the last item:
/^([1-9]\d{5})((19|20)\d{2})(0[1-9]|10|11|12)(0[1-9]|[1-2]\d|30|31)\d{3}(? :\d|x)$/i
// Id number
let str = '130222195202303210'.
reg =/^([1-9]\d{5})((19|20)\d{2})(0[1-9]|10|11|12)(0[1-9]|[1-2]\d|30|31)\d{3}(\d|x)$/i;
console.log(reg.exec(str));
console.log(str.match(reg));
//["130222195202303210", "130222", "1952", "19", "02", "30", "0", index: 0, input: "130222195202303210", groups: undefined]
Copy the code
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
- In a string
match
Method can capture all matched data in a single execution (the re must also be set to g) - When I add g,
match
Can’t get things in small groups
let reg = /\d+/g;
console.log('name2020name2020'.match(reg));/ / / "2020", "2020"]
Copy the code
// Capture both {0} and 0
let str = '{0} year {1} month ';
reg = /\{(\d)\}/g;
console.log(reg.exec(str));
console.log(str.match(reg));
Copy the code
3.3 Replace (Method on string prototype)
The word itself means string replacement. STR = str.replace(reg,func);
- First, reg and func will be matched. Once the match is captured, the func function will be executed once
- The result of each capture (as captured by exec) is passed to the func function
- Return what in a func function is equivalent to replacing the result of the grand re match with what in the original character
// Replace - with /(this method needs to be executed multiple times when the re is not used, but the re can be replaced once if g is added)
let str = '2020-04-09';
str = str.replace(/-/g.'/');
console.log(str);
Copy the code
let str = '{0} year {1} month ';
let reg = /\{\d\}/g;
str = str.replace(reg,(... args)=>{
console.log(args);// Stores the result of each re capture
return 1;
})
console.log(str);//'1 year 1 month '
Copy the code
4. Application of capture method in re
4.1 Time Format String
- Month and day less than ten fill zero
- Change the format to year, month and day
/ / method
let time = '2020-4-9';
let arr = time.match(/\d+/g);// Get each item
arr = arr.map(item= >item.length<2?'0'+item:item);
time = `${arr[0]}years${arr[1]}month${arr[2]}Day `;
console.log(time);
Copy the code
/ / method 2
let time = '2020-4-9';
let arr = time.match(/\d+/g);// Get each item
arr = arr.map(item= >item.length<2?'0'+item:item);
let template = '{0} year {1} Month {2} day ';
template = template.replace(/\{(\d+)\}/g, (value, group) => {
return arr[group]; //=> Replace the result of the match with that of the TEMPLETE large re
});
console.log(template);
Copy the code
/ / method 3
let time = '2020-4-9';
String.prototype.formatTime = function formatTime(template) {
let arr = this.match(/\d+/g).map(item= > {
return item.length < 2 ? '0' + item : item;
});
template = template || '{0} year {1} Month {2} day {3} {4} minutes {5} seconds';
return template.replace(/\{(\d+)\}/g, (_, group) => {
return arr[group] || "00";
});
};
console.log(time.formatTime());
Copy the code
4.2 The maximum number of occurrences of a character in a string
/ / method
let str = "qwerttydsdsssfggg";
let ary = [...new Set(str.split(' '))];
let max = 0;
let code = ' ';
for (let i = 0; i < ary.length; i++) {
// Create a regular match character
let reg = new RegExp(ary[i], 'g');
// Use match to find out where the corresponding character appears in the string, and take the length of the array returned by match, i.e. the number of occurrences of the corresponding string
let val = str.match(reg).length;
// Update the most frequently occurring character and number
if (val > max) {
max = val;
code = ary[i];
} else if (val === max) { // Handle the same number of different characters
code = `${code},${ary[i]}`;
}
}
console.log(The characters that appear most frequently are:${code}, The Times are:${max}`);
Copy the code
/ / method 2
let str = "sfsdfsgdsdgdfg";
let obj = {};
// str.match(/[a-zA-Z]/g) <==> str.split('')
str.match(/[a-zA-Z]/g).forEach(item= > {
// Before each storage, verify that the object already contains this character, if there is, it is stored before, we can add the amount of 1
if(obj[item] ! = =undefined) {
obj[item]++;
return;
}
obj[item] = 1;
});
let max = 0.
result = ' ';
for (let key in obj) {
let val = obj[key];
if (val > max) {
max = val;
result = key;
} else if (val === max) {
result += ` |${key}`;
}
}
console.log(max, result);
Copy the code
/ / method 3
let str = "sfsdfsdsfdgffd";
let arr = str.split(' ').sort((a, b) = > {
// Compare characters
return a.localeCompare(b);
});
let max = 1.
result = ' '.
temp = 1;
for (let i = 0; i < arr.length - 1; i++) {
let curr = arr[i],
next = arr[i + 1];
if (curr === next) {
temp++;
if (temp > max) {
max = temp;
result = curr;
}
} else {
temp = 1;
}
}
console.log(max, result);
Copy the code
4 / / method
let str = "sfsdsdgsdgsg";
str = str.split(' ').sort((a, b) = > a.localeCompare(b)).join(' ');
// console.log(str); //=>"aeefghhhiilnnoopsuuuxzz"
let ary = str.match(/([a-zA-Z])\1+/g).sort((a, b) = > b.length - a.length);
let max = ary[0].length,
res = [ary[0].substr(0.1)];
for (let i = 1; i < ary.length; i++) {
let item = ary[i];
if (item.length < max) {
break;
}
res.push(item.substr(0.1));
}
console.log('most frequently occurring character:${res}Appeared,${max}Time `);
Copy the code
5 / / method
let str = "fdsgsgdfhi".
max = 0.
res = [],
flag = false;
str = str.split(' ').sort((a, b) = > a.localeCompare(b)).join(' ');
for (let i = str.length; i > 0; i--) {
let reg = new RegExp("([a-zA-Z])\\1{" + (i - 1) + "}"."g");
str.replace(reg, (content, $1) = > {
res.push($1);
max = i;
flag = true;
});
if (flag) break;
}
console.log('most frequently occurring character:${res}Appeared,${max}Time `);
Copy the code
4.3 Obtaining The Parameter Information in the URL (Which May Also Contain HASH Values)
String.prototype.queryURLParams = function queryURLParams() {
let obj = {};
// Hash value processing
this.replace(/#([^?=#&]+)/g, (_, group) => obj['HASH'] = group);
// Handle the question mark parameter message
this.replace(/([^?#=&]+)=([^?#=&]+)/g, (_, group1, group2) => {
obj[group1] = group2;
});
return obj;
};
let str = 'http://www.baidu.cn/?lx=1&from=weixin&name=xxx#video';
let obj = str.queryURLParams();
console.log(obj);
Copy the code
4.4 Chromatic: Realize millennial character processing
String.prototype.millimeter = function millimeter() {
return this.replace(/ \ d {1, 3} (? =(\d{3})+$)/g, value => {
return value + ', ';
});
};
let str = "2312345638";
str = str.millimeter();
console.log(str); / / = > "2312345638"
Copy the code
Writing here, the study of re can be said to be almost mastered, (you must recall, this is what, to be crazy, ha ha ha. It is very stupid, but we also have to take out the milk to learn it, hahaha). Finishing is not easy, move small hands, leave a careful heart for the little woman.