Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the regular expression functions in JS

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly talks about "what are the regular expression functions in JS". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the regular expression functions in JS.

In JavaScript, the functions that can use regular expressions are (excluding outdated methods):

RegExp.prototype

RegExp.prototype.test ()

RegExp.prototype.exec ()

String.prototype

String.prototype.match ()

String.prototype.matchAll ()

String.prototype.replace ()

String.prototype.replaceAll ()

String.prototype.search ()

String.prototype.split ()

RegExp.prototype

First of all, we are going to talk about two methods on the RegExp object.

RegExp.prototype.test ()

Function: to detect whether there is a regular match in a given string

Code example:

A simple match is used to determine whether the match is successful according to the result of the match.

Const reg = /\ d {4} -\ d {2} -\ d {2} /; const str1 = '2000-02-22; const str2 =' 20-20-20; console.log (reg.test (str1)); / / true console.log (reg.test (str2)); / / false

The above regular expression does not set the global marker g, so we should be more careful when using this method if we set the global marker. Because if the regular expression sets the global identifier g, then for the same regular expression, if the match is successful when running the test method, it will modify the lastIndex property of the regular object, which may cause some problems in the next match. Let's take a look at an example.

Const reg = / abc/g; const str1 = 'abcd'; const str2 =' abcdabcd'; console.log (reg.lastIndex); / / 0 console.log (reg.test (str1)); / / true console.log (reg.lastIndex); / / 3 console.log (reg.test (str1)); / / false console.log (reg.lastIndex); / / 0 console.log (reg.test (str2)); / / true console.log (reg.lastIndex) / / 3 console.log (reg.test (str2)); / / true

The above example is a good illustration of this situation. If we set the global identifier g, as long as our current match is successful, then there may be a problem if we use the same rule to match again, because the previous successful match results in a change in the value of the lastIndex property of the regular expression object, so the next match starts from the lastIndex position. So there may be some problems.

Note: if you are using the test method, you need to pay attention to whether the regular expression has an g identifier. If this regular expression needs to be matched multiple times, it is best not to set the g identifier. Unless you know you really need to do it.

Use the scene:

If there is such a requirement, you need to determine whether the user name entered by the user meets the requirement, as follows: (1) the length of the user name needs to be 8-16 digits. (2) the user name can contain numbers, letters (both uppercase and lowercase), and underscores. (3) numbers and letters must be included.

Of course, for you who are familiar with regular expressions, this is not a problem, and a problem that can be solved with one line of code will never be solved with two lines of code. You can quickly solve this problem by using the test method.

Const validNameRE = / ^ (? = _ * (?:\ dkeeper * [a-zA-Z] + | [a-zA-Z] + _ *\ d+))\ w {8pm 16} $/; / / if this is the user name entered by the user, const userInputName = '1234567890; / / check whether the user name entered by the user meets the requirement const isValidName = validNameRE.test (userInputName); / / false

In normal development, if we need to determine the hosting environment of the page, we will also use the test method to determine the environment of the current page. For example, if you need to determine whether the current page is in an iPhone environment, you might write a judgment like this:

Const iPhoneReg = / iPhone/; console.log (iPhoneReg.test (navigator.userAgent)); / / true

RegExp.prototype.exec ()

Purpose: this method is a more common method, which matches in a given string and returns an array of matching results or null. Usually we use this method to extract some strings from the string that match the match.

Code example:

It is important to note that if there is no match, the result returned is null, not an empty array []. So when we need to determine whether there is a matching result, we can't feel that the returned value is an empty array [].

Const reg1 = / (\ d {2}): (\ d {2}): (\ d {2}) /; const str1 = 'Sat Aug 22 2020 17:31:55 GMT+0800 (China Standard time)'; const str2 = 'Sat Aug 22 2020; console.log (reg1.exec (str1)) / ["17:31:55", "17", "31", "55", index: 16, input: "Sat Aug 22 2020 17:31:55 GMT+0800 (China Standard time)", groups: undefined] console.log (reg1.exec (str2)); / / null

As we can see from the above code, if there is no match, the result returned is null. If the match is successful, the result returned is an array. In this result array, item 0 represents the content of the regular expression match. Item 1. N represents the capture of parentheses in the regular expression, and for the above example, item 1. 3 represents the time of capture. The array has additional attributes index and input, where index represents the position of the string matched by the regular expression in the original string. Input represents the original string to be matched.

Note:

Notice whether the regular expression has the g identifier set, and if the g identifier is set, then we can use this regular expression for a global search. You can look at the following code example.

Const reg = /\ d reg.lastIndex g; const str = '654321; let result; while ((result = reg.exec (str) {console.log (`The number matched this time is: ${result [0]}, the value of the lastIndex of the regular expression is: ${reg.lastIndex} `);}

The output is as follows:

The matching number is: 6, the lastIndex value of the regular expression is: 1 the number matched this time is: 5, the lastIndex value of the regular expression is: 2 the matching number is: 4, the lastIndex value of the regular expression is: 3, the lastIndex value of the regular expression is: 4, the matching number is: 2 The value of the lastIndex of the regular expression is: 5 the matching number is: 1, and the value of the lastIndex of the regular expression is: 6

It is important to note that if the g identifier is not set for the matching regular expression above, or if the literal amount of the regular expression is used in the conditional judgment of the while loop, it will cause a "dead loop." Because that way, the lastIndex attribute of the regular expression will be 0 at the beginning of each loop, causing the result to always have a value, resulting in a "dead loop". So we have to be careful when using the exec method in the while loop.

Usage scenario: this method is mainly used to extract some key information we want from the original text, so whenever it is such a requirement scenario, we can use the exec method of regular expressions to deal with it. For example:

The links in the user input content are automatically identified, and then the corresponding link content is processed in style and function.

You can extract the query parameters in url, and if we need to extract the query parameters in url ourselves, using the exec method is also an option.

If you have read the source code of vue, the exec method is used in the text parsing in the compilation module. If you are interested, you can take a look at the relevant code implementation.

Of course, there are many scenarios that can be dealt with using the exec method. Have you ever used the exec method to deal with some problems in your usual development? You can leave a message below and let's discuss it together to deepen our understanding of this method.

String.prototype

Next, let's talk about some of the methods of regularization in String.prototype.

String.prototype.match ()

Purpose: this method returns the result of a string matching a regular expression.

Code example:

Const reg = /\ d reg; const str = 'abc123'; console.log (str.match (reg)); / / ["1", index: 3, input: "abc123", groups: undefined]

Note:

1. The return result that does not match is null.

Const reg = /\ d reg; const str = 'abc'; console.log (str.match (reg)); / / null

two。 Whether the g identifier is set, if g is not set, the return result of match is the same as that of the corresponding exec. If the g identifier is set, the result returned is a collection of results that match the regular expression.

Const reg = /\ d reg g; const str = 'abc123'; console.log (str.match (reg)); / / ["1", "2", "3"]

3. If the match method does not pass an argument, the result returned is ['], an array containing an empty string.

Const str = 'abc123'; console.log (str.match ()); / / [", index: 0, input:" abc123 ", groups: undefined]

4. If the parameter passed by the match method is a string or number, new RegExp (regex) is implicitly called internally, turning the passed parameter into a regular expression.

Const str = 'abc123'; console.log (str.match (' b')); / / ["b", index: 1, input: "abc123", groups: undefined]

Use the scene:

Simply get the query parameters in url:

Const query = {}; / / first use the regular with the g identifier to indicate that the global lookup const kv = location.search.match (/\ wband =\ wagape g); if (kv) {kv.forEach (v = > {/ / use the regular without the g identifier, you need to get the captured content const Q = v.match (/ (\ w*) = (\ w*) /) in parentheses) Query [Q [1]] = Q [2];};}

String.prototype.matchAll ()

What this method does: this method returns an iterator that contains all the captured contents of matching regular expressions and parentheses in regular expressions. It is important to note that this method is compatible. For more information, please see String.prototype.matchAll.

Code example:

Const reg = / (\ w*) = (\ w*) / g; const str = 'axiaqian _ 1 _

String.prototype.matchAll ()

Note:

1. Similar to the match method, if the parameter passed to the matchAll method is not a regular expression, then new RegExp (obj) is implicitly called to convert it to a regular expression object. The regular expression passed to matchAll needs to have the g identifier set, and if the g identifier is not set, an error will be thrown.

Const reg = / (\ w*) = (\ w*) /; const str = 'axiaqian _ 1 _; console.log ([... str.matchAll (reg)]); / / Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument

two。 In cases where matchAll can be used, it is easier to use matchAll than to use the exec method. Because in cases where global matching is needed, the exec method needs to be used in conjunction with loops, but with matchAll, loops can be avoided.

3. The matchAll method does not update the lastIndex property of the regular expression during string matching. More details can be found in String.prototype.matchAll ().

Use the scene:

Let's practice it with the small function of getting query parameters in url above:

Const query = {}; const kvs = location.search.matchAll (/ (\ w*) = (\ w*) / g); if (kvs) {for (let kv of kvs) {query [kv [1]] = kv [2];}} console.log (query)

String.prototype.replace ()

Function: this method should be commonly used in normal development, so its function is to use the replacement replacement to replace the string in the original string that matches a certain pattern pattern. Where the replacement can be a string, or the return value can be a function of a string; the pattern can be a regular expression or a string.

Code example:

Since the input parameters of this function can be of different types, let's practice each type of input parameters.

1. Pattern is a string, and replacement is also a string. This form is often used in peacetime development.

Const pattern = 'a'; const replacement =' A'; const str = 'aBCD'; console.log (str.replace (pattern, replacement)); / / ABCD

2. Pattern is a regular expression and replacement is a string.

Const pattern = / _ (\ d) _ /; const replacement = "--$$--$&-- $`--$'--$1muri -"; const str = 'aaa__1__bbb'; console.log (str.replace (pattern, replacement)); / / aaa--$--__1__--aaa--bbb--1--bbb

If replacement is a string, you can use some special variables in this string, as shown in Specifying a string as a parameter.

Pattern is a regular expression and replacement is a function.

Const pattern = / _ (?\ d) _ _ /; const replacement = function (match, p1, offset, str, groups) {console.log (the string matched by `is: ${match}\ nThe matching position is: ${offset}\ nThe original string to be matched is: ${str}\ nThe captured content named is: ${JSON.stringify (groups)}`) Return'=';}; const str = 'aaa__1__bbb'; console.log (str.replace (pattern, replacement)); / / aaa=bbb

The output of the console is as follows:

The matching string is: _ _ 1matches _ the captured content is: 1 the matching position is: 3 the original string to be matched is: the captured content named by aaa__1__bbb is: {"number": "1"}

If you don't know much about the fact that replacement is a function, you can take a look at Specifying a function as a parameter. There will be a detailed explanation, so I won't explain it here.

Note:

It is important to note that when our pattern is a regular expression, we should pay attention to whether the g identifier is set, because if the g identifier is not set, there will only be one match. If the g identifier is set, a global match will be performed.

Use the scene:

For the front end, it is a common requirement to validate the user's input. If we have an input box that only allows users to enter numbers, we can deal with it like this:

Const reg = /\ DUnig; const str = 'abc123'; console.log (str.replace (reg,')); / / 123

This ensures that the user's input is only numeric.

String.prototype.replaceAll ()

As of August 2020 the replaceAll () method is supported by Firefox but not by Chrome. It will become available in Chrome 85.

This method is similar to the replace method, and you can tell from the name that replaceAll is a global replacement. Because of the compatibility of this method, we need to experiment on the Firefox browser.

Const pattern = 'a'; const replacement =' A'; const str = 'aBCDa'; console.log (str.replace (pattern, replacement)); / / ABCDa console.log (str.replaceAll (pattern, replacement)); / / ABCDA

Const pattern = / a pattern; const replacement = 'A'; const str =' aBCDa'; console.log (str.replace (pattern, replacement)); / / ABCDa console.log (str.replaceAll (pattern, replacement)); / / Uncaught TypeError: replaceAll must be called with a global RegExp

String.prototype.search ()

Code example:

Const reg = /\ d console.log; const str1 = '123; const str2 =' abc'; console.log (str1.search (reg)); / / 0 console.log (str2.search (reg)); / /-1

Note:

If the parameter passed in is not a regular expression, new RegExp (regexp) is implicitly called to convert it to a regular expression.

When no match is found, the returned value is-1; therefore, when you use this method to make a judgment, you should note that only when the return value is-1, the corresponding match is not found.

Use the scene:

If you need to find the position of a specific match in a string, you can use the search method.

Const reg = /\ d const str; const str = 'abc6def'; console.log (str.search (reg)); / / 3

String.prototype.split ()

Function: split a string according to the splitter, and form a new array of the segmented string fragments, where the splitter separator can be a string or a regular expression.

Code example:

1. The splitter separator is a string:

Const str = 'hello, Worldwide, console.log (str.split ('')); / / ["h", "e", "l", "l", "o", "o", "w", "o", "r", "l", "d", "!"]

two。 The splitter separator is a regular expression:

Const str = 'abc1abc2abc3'; const separator = /\ w (? =\ d) /; console.log (str.split (separator)); / / ["ab", "1ab", "2ab", "3"]

Note:

1. If the split method does not pass an argument, it returns an array containing the original string:

Const str = 'hello, worldviews; console.log (str.split ()); / / ["hello, world!"]

two。 Because JavaScript strings are encoded using UTF-16, the encoding uses a 16-bit encoding unit to represent most common characters and two encoding units to represent less commonly used characters. So for some less commonly used characters, there may be some problems when using the split method for string segmentation:

Const str ='?'; console.log (str.split ('')); / / ["girls", "girls"]

How to solve this type of problem? The first method is to use the extension operator of the array:

Const str ='?'; console.log ([... str]); / / ["?", "?"]

The second method is to use a regular expression with a u identifier set:

Const str ='?'; const separator = / (? = [\ s\ S]) / u; console.log (str.split (separator)); / / ["?", "?"]

If the regular representation parameter passed in contains captured parentheses, the captured content is also included in the returned array:

Const str = 'abc1abc2abc3'; const separator = / (\ w) (? =\ d) /; console.log (str.split (separator)); / / ["ab", "c", "1ab", "c", "2ab", "c", "3"]

The split method can also pass in a second parameter to control the length of the returned array:

Const str = 'hello, worldviews; console.log (str.split (', 3)); / / ["h", "e", "l"]

Use the scene:

In actual development, the most common scenario is to convert a string into an array:

Const str ='a _ JS _ Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report