Thanks for checking out my new article: Regular Expressions for JavaScript Hacks You Should Know
Regular expressions are logical, flexible, and functional. ② It can quickly achieve complex control of strings in a minimalist manner.
Use of regular expressions
Concept: regular expressions in JS are the creation and use of regular expressions stored as objects
//1 Creates a regular expression
let rg = / 123 /
// Expression validation
console.log(rg.test('123'));
Call test() and pass in the string or number you want to validate. Test returns true or false
Copy the code
The border characters ^ and $
So the first thing we have to figure out is what does this notation mean?^
This is the starting position $
That’s where it ends. Ok, so let’s look at the code.
let rg = /^acb$/ // AcB must start with A and end with B
console.log(rg.test('acb')); //true
console.log(rg.test('bca')); //false
console.log(rg.test('cab')); //false
Copy the code
The character class []
Represents a series of character choices that match only one of them
if[]
There is a^
Notice the opposite meaning.
// Let's look at the following code
let rg = /[acb]/ // Return true whenever a or b or c is included
console.log(rg.test('abc')); //true
console.log(rg.test('bca')); //true
console.log(rg.test('test')); //false
Copy the code
Scope operator [-]
Represents a restriction on the type obtained
let rg = /^[a-z]$/ // Return true for all 26 letters
console.log(rg.test('abc')); //true
console.log(rg.test('bca')); //true
console.log(rg.test('test')); //true
console.log(rg.test(1)); //false
console.log(rg.test('A')); //false // Case sensitive.
// If you want to add multiple validation rules, just look at the previous character spelling. For example, IF I want to verify that the username supports case and number, I can write like this.
let rg = /^[a-zA-Z0-9]$/ // Be careful not to add Spaces between them.
Copy the code
Quantifier {}
The number of occurrences of a certain pattern. The validation rule we just wrote can only judge a single character, which is not practical in real development, so we need to limit the number of occurrences of a character.
}
let rg = / ^ [a zA - Z0-9] {6, 8} $/ // No Spaces! Indicates that the character being validated has at least six and up to eight bits
console.log(rg.test('test')); //false
console.log(rg.test('test11')); //false
console.log(rg.test('123456789')); //false
Copy the code