Regular expressions describe a pattern of string matching, which can be used to check whether a string contains a certain substring, replace the matching substring, or take out a substring that meets a certain condition from a string, etc.
Front-end regular expression writing
1. Writing method
Writing method one
/regex/modifier
Modifier
- /i (Ignore case)
- /g (Full text to find all matching characters that appear)
- /m (multiple line search)
- /gi(Full text search, ignoring upper and lower case)
- /ig (full text search, ignoring upper and lower case)
Example: /a/gi Find a content
By default, only one modifier is matched
Writing method two
let a = new RegExp('/regex/','modifier')
2. Several common methods
Methods can retrieve the specified value within a string, or find a match for one or more regular expressions.
Returned content
["Matched content", index: 3, input: "String object", groups: undefined]
If the regexp modifier is /g, the object is returned as an array
grammar:
(str)
(regexp)
Take a lookup string a in abc as an example
'aabc' .match('a') Match only the first one 'aabc' .match(/a/) Match only the first one
Used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression
grammar:
('The first string found','Modified string')
(regexp(all replaced by the content matched by the regular expression), 'modified string')
His usage is similar to match, but what he returns is the index
grammar:
('searchvalue')
(regexp)
Method is used to detect whether a string matches a pattern. If the string contains matching text, it returns true, otherwise it returns false.
grammar:
(stringObject)
like
/a/.test('a') #Return true/a/.test('ac') #Return true/a/.test('c') #returnfalse
The method is to retrieve the match of regular expressions in the string. If the match is reached, it returns an array with the results. If there is no match, it returns a null.
(stringObject)
Actually, it's similar to match, but just return to the fill-in position
But there is one thing
('c'.exec('c')); #There will be an error('c'.match('c')); #Will matchc
Summarize
The above is the front-end regular expression writing and commonly used methods introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!