Article Directory
- 1 Overview of regular expressions
- 2 Use of regular expressions in Javascript
- 3 Special characters in regular expressions
- Composition of 3.1 Regular Expressions
- 3.2 Boundary Character
- 3.3 Character Class
- 3.4 Quantifier
- 3.5 Bracket Summary
- 3.6 Predefined Classes
- 4 Replacement in Regular Expressions
- summary
1 Overview of regular expressions
1.1 What is a regular expression
Regular expressions are patterns used to match combinations of characters in strings.Regular expressions are also objects in Javascript.
Regular tables are often used to retrieve and replace text that conforms to a pattern (rule), such as a validation form: User name forms can only enter letters, numbers, or underscores in English, and nicknames in Chinese (match).In addition, regular expressions are often used to filter out sensitive words in page content, or to get specific parts (extracts) we need from strings.
1.2 Regular Expression Features
- Flexibility, logic and functionality are very strong
- Complex control of strings can be quickly achieved in extremely simple ways
- More difficult to understand
2 Use of regular expressions in Javascript
2.1 Create regular expressions
- Created by the constructor of the RegExp object
var variable name= new RegExp(/expression/)
// Creating Objects with RegExp var regexp = new RegExp(/123/) console.log(regexp)
- Create by Literal Quantity
var variable name=/expression/
var rg = /123/ console.log(rg)
2.2 Testing regular expression test
The test() regular object method, which detects whether a string conforms to this rule, returns true or false with the parameter Test String.
regexObj.test(str)
- regexObj is a written regular expression
- str Text we want to test
- Is to detect whether str text conforms to the regular expression specification we wrote
var rg = /123/ console.log(rg.test(123)) //true console.log(rg.test('abc')) //false
3 Special characters in regular expressions
Composition of 3.1 Regular Expressions
A regular expression can be composed of simple characters, such as/ab c/, or a combination of simple and special characters, such as/ab*c/.Special characters, also known as metacharacters, are special symbols in regular expressions.
As there are many special characters, they are not listed here anymore. For reference:
MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
Here you can divide metacharacters into several types of learning:
3.2 Boundary Character
Boundary characters (placeholders) in regular expressions are used to indicate where a character is, mainly two characters.
If both ^ and $exist, an exact match is reached
var rg= /abc/ //No quotation marks are required in regular expressions // /abc/Returns true as long as the string contains ABC console.log(rg.test('abc')) // true console.log(rg.test('abcd')) // true console.log(rg.test('aabcd')) // true var reg = /^abc/ console.log(rg.test('abc')) // true console.log(rg.test('abcd')) // true console.log(rg.test('aabcd')) // false var reg = /^abc$/ //Exact match, abc string is required to conform to specification console.log(rg.test('abc')) // true console.log(rg.test('abcd')) // false console.log(rg.test('aabcd')) // false console.log(rg.test('abcabc')) // false
3.3 Character Class
Indicates that there is a series of characters to choose from, as long as one of them is matched, all the characters to choose from are placed in square brackets
var rg = /[abc]/; //Returns true as long as it contains a or b or c console.log(rg.test('andy')) //true var rg = /[abc]/; //Returns true as long as it contains a or b or c console.log(rg.test('baby')) //true console.log(rg.test('color')) //true console.log(rg.test('red')) //false var rg = /^[abc]$/ //Choose one of the three letters with a or b or c to return true console.log(rg.test('aa')) //false console.log(rg.test('a')) //true console.log(rg.test('b')) //true console.log(rg.test('c')) //true console.log(rg.test('abc')) //false var rg = /^[a-z]$/ //26 English letters Any letter returns true var rg = /^[a-zA-Z]$/ //26 English letters (upper case and lower case) Any one returns true var rg = /^[a-zA-Z0-9_-]$/ console.log(rg.test('c')) //true console.log(rg.test('B')) //true console.log(rg.test('_')) //true console.log(rg.test('8')) //true console.log(rg.test('-')) //true //If there is ^ in the middle bracket, it means the opposite. Don't confuse the boundary character ^ var rg = /^[^a-zA-Z]$/
3.4 Quantifier
Quantifiers are used to set the number of times a pattern occurs
var reg = /^a*$/ console.log(reg.test(''))// true console.log(reg.test('a'))// true console.log(reg.test('aaa'))// true var reg = /^a+$/ console.log(reg.test(''))// false console.log(reg.test('a'))// true console.log(reg.test('aaa'))// true var reg = /^a?$/ console.log(reg.test(''))// true console.log(reg.test('a'))// true console.log(reg.test('aaa'))// false var reg = /^a{3}$/ console.log(reg.test(''))// false console.log(reg.test('a'))// false console.log(reg.test('aaa'))// true var reg = /^a{3,}$/ console.log(reg.test(''))// false console.log(reg.test('a'))// false console.log(reg.test('aaa'))// true console.log(reg.test('aaaaa'))// true var reg = /^a{3,5}$/ //Don't leave spaces after commas {3,5} console.log(reg.test(''))// false console.log(reg.test('a'))// false console.log(reg.test('aaa'))// true console.log(reg.test('aaaaa'))// true
User name validation
- If the username input is valid, the message is: the username is valid and the color is green
- If the username input is not valid, the following message is: the username does not conform to the specification and the color is green
User name validation analysis:
- User names can only consist of letters, numbers, underscores or dashes in English, and are 6-16 digits long.
- Prepare this regular expression pattern first
- If it conforms to the regular specification, add the right class to the space tag that follows.
- If it does not conform to the regular specification, add the wrong class to the space tag that follows.
<input type="text" class="uname"> <span>enter one user name</span> <style> span { color: #aaa; font-size: 14px; } .right { color: green; } .wrong { color: red; } </style>
var reg=/^[a-zA-Z0-9-_]{6,16}$/ var uname = doucument.querySelector('.uname'); var spn = doucument.querySelector('span'); uname.onblur = function() { if(res.test(this.value)){ span.className='right' span.innerHTML = 'User name input format is correct' } else { span.className='wrong' span.innerHTML = 'User name input format error' } }
3.5 Bracket Summary
- Braces: quantifiers indicate the number of repetitions
- Brackets: Character collection.Match any character in square brackets
- Parentheses: indicates priority
//Brackets var reg = /^[abc]$/ //a||b||c //Braces var reg = /^abc{3}$/ //It just lets c repeat three times //parentheses var reg = /^(abc){3}$/ //abc repeat three times
3.6 Predefined Classes
Predefined classes are abbreviations of some common patterns when they refer to
Stand Number Verification
var reg= /^\d{3}-\d{8}|\d{4}-\d{7}$/ // | Yes or Meaning var reg= /^\d{3,4}-\d{7,8}|\d{4}-\d{7}$/
4 Replacement in Regular Expressions
4.1 replace replacement
The replace() method implements a substitution string operation, and the substitution parameter can be a string or a regular expression.
stringObject.replace(regxp/substr, replacement)
- First parameter: substituted string or regular expression
- Second parameter: string to replace with
- Return value is a new string replaced
var str = 'lanfeng and qianduan' var newStr = str.replace('front', 'qianduan') console.log(newstr)
Message Filter Sensitive Words
<textarea name="" id="message"></textarea> <button>Submit</button>
var text = document.querySelector('textarea'); var btn = document.querySelector('button'); var div = doucment.querySelector('div'); btn.onclick = function () { div.innerHTML = text.value.replace(/Passion/g, '**') }
4.2 Regular Expression Parameters
/expression/[switch]
There are three values for which switch (also known as modifier) matches in a pattern
summary
This article mainly shares some points of knowledge and usage of regularity in javascript.