In the previous series of articles, we learned a lot about regular expressions. So as a front-end engineer, if you want to apply this knowledge to your daily development, you need to know what functions in JavaScript can use regex? And then what are their respective functions? What should I pay attention to? Only by mastering the usage scenarios of each method, can we quickly think of which method is the most efficient and the best when we need to use it.

These are indeed some basic knowledge, but I believe that there should be many students have not systematically studied these knowledge side. Trust me, if you can finish reading this article, you will learn something new. Know the purpose of each method, use scenario, learn to choose the right method in the right scenario. Of course, you can also learn what to do with these methods so you don’t get bogged down using them later.

The code examples in this article are in the Chrome browser unless otherwise noted. The content of this article is quite long, it is suggested to collect it first, you can slowly look at it later.

In JavaScript, functions that can use regular expressions are (to the exclusion of obsolete 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

The first thing we’ll look at are two methods on the RegExp object

RegExp.prototype.test()

  • Function: Checks whether there are matches in a given string that satisfy the re
  • Code examples:

Simple matching, according to the matching result to determine whether the match is successful.

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

The above regular expression does not set the global g flag. If it does, we need to be careful when using this method. If the regular expression sets the global identifier G, then the test method will change the lastIndex property of the same regular expression if the match is successful, which may cause some problems the next time the regular expression is matched.

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
Copy the code

The above example illustrates this situation very well, if we set the global identifier g, as long as our current matching is successful, then if again using the same regular match may appear problem, because a successful match on lead to regular expression objects lastIndex attribute’s value has changed, So the next time you do a match, you start at lastIndex, so you might have some problems.

  • Note: If you use the test method, check whether the regular expression contains the G identifier. If the regular expression requires multiple matches, it is best not to set the G identifier. Unless you know you really need to.

  • Usage Scenarios:

If there is 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 must be 8-16 characters. (2) The username can contain numbers, letters, and underscores (_). (3) Numbers and letters are mandatory.

Of course, for those of you familiar with regular expressions, this is not a problem. A problem that can be solved with one line of code should never be solved with two lines of code. You can quickly solve this problem by using the Test method.

const validNameRE = / ^ (? = _ * (? : \ d + _ + | * [a zA - Z] [a zA - Z] + _ * \ d +)) \ $/ w 16th {8};
// If this is the username entered by the user
const userInputName = '1234567890';
// Check whether the user name entered by the user meets the requirements
const isValidName = validNameRE.test(userInputName); // false
Copy the code

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

const iPhoneReg = /iPhone/;
console.log(iPhoneReg.test(navigator.userAgent));  // true
Copy the code

RegExp.prototype.exec()

  • Function: This method is a common method that matches a given string and returns either an array of matched results or null. Normally we would use this method to extract strings from a string that match.

  • Code examples:

Note that if there is no match, the result is null, not an empty array []. So when we need to determine whether there is a match, we should not 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 ';
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 ", Groups: undefined]
console.log(reg1.exec(str2));  // null
Copy the code

As you can see from the above code, null is returned if there is no match. If the match is successful, the result is an array. In this result array, the 0th item represents what the regular expression matches. Among them 1.. The n term represents what is captured in parentheses in the regular expression. For the example above, the first.. Three represents the hour and second of the capture time. Arrays also have additional attributes index and input, where index represents the position of the string in the original string that the regular expression matches. Input represents the original string to be matched.

  • Matters needing attention:

    • Note whether the regular expression is setgIdentifier, if setgIdentifier, so we can use this regular expression to search globally. Take a look at the code example below.
    const reg = /\d/g;
    const str = '654321';
    let result;
    while ((result = reg.exec(str))) {
      console.log(
        'The number matched this time is:${result[0]}The value of lastIndex of the regular expression is:${ reg.lastIndex }`
      );
    }
    Copy the code

    The output is as follows:

    The matched number is 6, and the lastIndex value of the regular expression is: 1 The matched number is 5, and the lastIndex value of the regular expression is: 2 The matched number is 4, and the lastIndex value of the regular expression is: 3 The matched number is: 3. The value of lastIndex in the regular expression is: 4. The value of lastIndex in the regular expression is: 5Copy the code

    Note that if the regular expression matched above does not have a G identifier, or if the condition of the while loop uses a literal of the regular expression, it will cause an “infinite loop”. Because then, the lastIndex property of the regular expression would be 0 at the beginning of each loop, resulting in a constant value of result, resulting in an “infinite loop.” So we have to be careful when using the exec method in the while loop.

  • Usage scenarios: This method is mainly used to extract some of the key information we want from the original text, so as long as such a requirement scenario can be used to handle the regular expression exec method. Such as:

    • Links in user input content are automatically recognized, and then the corresponding link content is styled and functionally processed.
    • Query parameters can be extracted from the URL, if we need to extract the query parameters from the URL ourselvesexecMethod is also an option.
    • If you have read the vue source code, text parsing in the build module uses the Exec method, if you are interested you can take a look at the code implementation.

    Of course, there are many scenarios that can be handled by exec method. Have you ever used exec method to deal with some problems in your daily development? You can leave a comment below, we all discuss, deepen the understanding of this method.

String.prototype

Let’s take a look at some of the String. Prototype methods for regeting.

String.prototype.match()

  • Action: This method returns the result of a string matching a regular expression.

  • Code examples:

const reg = /\d/;
const str = 'abc123';
console.log(str.match(reg));  // ["1", index: 3, input: "abc123", groups: undefined]
Copy the code
  • Matters needing attention:

    • The return result of no match isnull.
    const reg = /\d/;
    const str = 'abc';
    console.log(str.match(reg));  // null
    Copy the code
    • Is it setgIdentifier if not setgWords,matchIs returned with the correspondingexecThe return result is the same. If you set it upgIdentifier, the result returned is a collection of results that match the regular expression.
    const reg = /\d/g;
    const str = 'abc123';
    console.log(str.match(reg));  / / / "1", "2", "3"]
    Copy the code
    • ifmatchIf the method passes no arguments, the result returned is[...], an array containing empty strings.
    const str = 'abc123';
    console.log(str.match());  // ["", index: 0, input: "abc123", groups: undefined]
    Copy the code
    • ifmatchMethods that pass a string or number are called implicitly internallynew RegExp(regex)To convert the passed parameter into a regular expression.
    const str = 'abc123';
    console.log(str.match('b'));  // ["b", index: 1, input: "abc123", groups: undefined]
    Copy the code
  • Usage Scenarios:

    Simply get query parameters in the URL:

    const query = {};
    // First use the re with the g identifier to represent the global lookup
    const kv = location.search.match(/\w*=\w*/g);
    if (kv) {
      kv.forEach(v= > {
          // To use the re without the G identifier, you need to get the captured content in parentheses
        const q = v.match(/(\w*)=(\w*)/);
        query[q[1]] = q[2];
      });
    }
    Copy the code

String.prototype.matchAll()

  • Action: This method returns an iterator containing all matched regular expressions and the captured contents of the parentheses inside the regular expression. It is important to note this method have compatibility, specific contents can view String. Prototype. MatchAll.

  • Code examples:

const reg = /(\w*)=(\w*)/g;
const str = 'a=1,b=2,c=3';
console.log([...str.matchAll(reg)]);
Copy the code

  • Matters needing attention:

    • Like the match method, if the argument 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; if it is not set, an error is thrown.

    const reg = /(\w*)=(\w*)/;
    const str = 'a=1,b=2,c=3';
    console.log([...str.matchAll(reg)]);  // Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument
    Copy the code
    • In cases where matchAll is available, it is more convenient to use matchAll than the exec method. Because the exec method needs to be used in conjunction with a loop in the case of global matching, the loop can be eliminated with matchAll.

    • The matchAll method does not update the lastIndex property of the regular expression during a string match. More details you can refer to a String. The prototype. MatchAll ().

  • Usage Scenarios:

Get query parameters from THE URL.

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);
Copy the code

String.prototype.replace()

  • Function: This method should be used in normal development, so it is used to replace the original string with a replacement of the pattern of the string. Where the substitution can be a string, or a function that returns a string; The pattern can be a regular expression or a string.

  • Code examples:

    Since this function can have different types of input parameters, let’s practice with each type.

    • Pattern is a string, replacement is also a string. This form is often used in normal development.
    const pattern = 'a';
    const replacement = 'A';
    const str = 'aBCD';
    console.log(str.replace(pattern, replacement));  // ABCD
    Copy the code
    • Pattern is a regular expression, replacement is a string.
    const pattern = /__(\d)__/;
    const replacement = "- $$- $& - $` - $1 $' -- -";
    const str = 'aaa__1__bbb';
    console.log(str.replace(pattern, replacement));  // aaa--$--__1__--aaa--bbb--1--bbb
    Copy the code

    If replacement is a string, you can specify a number of special variables in this string (see Specifying a String as a parameter).

    • Pattern is a regular expression, replacement is a function.
    const pattern = / __ (? 
            
             \d)__/
            ;
    const replacement = function(match, p1, offset, str, groups) {
      console.log('matches the string:${match}\n Captured the following:${p1}\n The matching position is:${offset}\n The original string to be matched is:${str}\n named capture content is:The ${JSON.stringify(groups)}`);
      return '= = = = = =';
    };
    const str = 'aaa__1__bbb';
    console.log(str.replace(pattern, replacement)); // aaa======bbb
    Copy the code

    The output of the console is as follows:

    The matching string is: __1__.1The matching position is:3The original string to be matched is: aaa__1__bbb the named catch is: {"number":"1"}
    Copy the code

    If you are not familiar with the situation of Specifying a function as a parameter, you will need to specify a function as a parameter in detail.

  • Matters needing attention:

    Note that when pattern is a regular expression, it is important to note whether the G identifier is set, because if the G identifier is not set, only one match will be made. If the G identifier is set, global matching is performed.

  • Usage Scenarios:

    Validation of user input is a common requirement for the front end. Suppose we had an input field that only allowed the user to enter numbers, we could do something like this:

    const reg = /\D/g;
    const str = 'abc123';
    console.log(str.replace(reg, ' '));  / / 123
    Copy the code

    This ensures that the user’s input is only numbers.

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 in that the name tells you that replaceAll is a global replacement. Because of compatibility issues with this approach, we need to experiment with Firefox.

const pattern = 'a';
const replacement = 'A';
const str = 'aBCDa';
console.log(str.replace(pattern, replacement));  // ABCDa
console.log(str.replaceAll(pattern, replacement));  // ABCDA
Copy the code
  • Matters needing attention: If passed to the functionpatternIf the argument is a regular expression, the regular expression must be setgIdentifier, otherwise an error will be thrown.
const pattern = /a/;
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
Copy the code

String.prototype.search()

  • Function: This method looks for a pattern in a string. If a pattern is found, returns the index at the beginning of the match. Returns -1 if not found.

  • Code examples:

const reg = /\d/;
const str1 = '123';
const str2 = 'abc';
console.log(str1.search(reg));  / / 0
console.log(str2.search(reg));  // -1
Copy the code
  • Matters needing attention:

    • If the argument passed is not a regular expression, new RegExp(RegExp) is implicitly called to convert it to a regular expression.

    • When no match is found, the return value is -1; So when you use this method, it’s important to note that only if the return value is -1, no match has been found.

  • Usage Scenarios:

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

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

String.prototype.split()

  • Separator splits a string according to the separator and forms a new array. Separator can be a string or a regular expression.

  • Code examples:

    • dividerseparatorIs a string:
    const str = 'hello, world! ';
    console.log(str.split(' '));  // ["h", "e", "l", "l", "o", ",", " ", "w", "o", "r", "l", "d", "!"]
    Copy the code
    • dividerseparatorIs a regular expression:
    const str = 'abc1abc2abc3';
    const separator = /\w(? =\d)/;
    console.log(str.split(separator));  // ["ab", "1ab", "2ab", "3"]
    Copy the code
  • Matters needing attention:

    • ifsplitIf the method does not pass arguments, it returns an array containing the original string:
    const str = 'hello, world! ';
    console.log(str.split());  // ["hello, world!"]
    Copy the code
    • becauseJavaScriptThe string is usedUTF-16Encoding, which uses a 16-bit encoding unit for most common characters and two encoding units for less common characters. So for some uncommon characters, in usesplitThere are some problems with the string split method:
    const str = '😀 😃 😄 😁 😆 😅';
    console.log(str.split(' '));  / / / "� �", ""," � ", "�", "�", "�", "�", "�", "�", "�", "�", "�"]
    Copy the code

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

    const str = '😀 😃 😄 😁 😆 😅';
    console.log([...str]);  // ["😀", "😃", "😄", "😁", "😃", "disk "," disk ", "disk "]
    Copy the code

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

    const str = '😀 😃 😄 😁 😆 😅';
    const separator = / (? =[\s\S])/u;
    console.log(str.split(separator)); // ["😀", "😃", "😄", "😁", "😃", "disk "," disk ", "disk "]
    Copy the code
    • If the regex parameter is passed with 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"]
    Copy the code
    • splitThe method can also pass in a second argument that controls the length of the returned array:
    const str = 'hello, world! ';
    console.log(str.split(' '.3));  // ["h", "e", "l"]
    Copy the code
  • Usage Scenarios:

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

const str = 'a/b/c/d/e';
console.log(str.split('/')); // ["a", "b", "c", "d", "e"]
Copy the code

conclusion

Once we can master the above methods, then in the actual development of regular expressions combined with the use of a tiger, it is a tiger, can improve the efficiency of development in some scenarios.

Of course, only by looking at the article is not very good to remember these knowledge points are firm, you need to practice one by one, so as to deepen their memory, to be able to remember more firmly.

If you want to learn more about regular expressions, check out my previous series of articles:

  • Explains how regular expressions match prime numbers
  • All you need to know about regular glances is this article
  • Regular Expression quantifier Matching Method (Part 1)
  • Want to write a more efficient regular expression? Try solidifying groupings and possession-first matching

If you have any comments or suggestions for this article, feel free to leave them in the comments below or here. Also welcome everyone to pay attention to my public number guanshan is not difficult to learn more practical front-end knowledge, let us work together to progress.