JS replaceAll and matchAll usage guidelines do not point north

Original link: https://www.zhangxinxu.com/wordpress/2022/08/js-replaceall-matchall/

by zhangxinxu from https://www.zhangxinxu.com/wordpress/?p=10499 Xin Space-Xin Life

This article welcomes sharing and aggregation. There is no need to reprint the full text. The copyright is respected. The circle is so large. If you need it urgently, you can contact for authorization.

Cover Image - Paper Airplane

First, let’s talk about replaceAll

The replaceAll API is a new API in the last year or two. It may not be supported by some browsers, such as the 360 ​​speed version (although the Chromium kernel is used, but the version is too old), as well as some old Android devices. .

I like this API very much. It can easily solve some of the more troublesome string processing requirements in the past.

For example, highlight matches for search keywords.

As shown in the figure below, search for the letter x, and the pinyin of the two characters in my name matches it:

name highlight

Huh? No, no, not this, it should be a double word match, that is, if my name is: Zhang Xinxin, when searching for “Xin”, both words should be highlighted.

I’ll upload the picture above, wait a minute…

character match

If you only match one character, you can use replace directly, which is as simple as an explosion.

 name = name.replace('xin', '<mark>xin</mark>');

But if you want all the “Xin” characters to be highlighted, replace will change from the old sixth to the second and fifth, and you can only use regular expressions to replace, because the content entered by the user input box is dynamic, so you can only use new RegExp() implementation.

 // Actual development, name = name.replace(new RegExp('xin', 'g'), '<mark>xin</mark>') in new RegExp();

However, using RegExp has two major disadvantages:

1. Difficult, the newcomer said that his concubine can’t remember it. Every time you use it, you have to look at the grammar. It’s not as easy to understand as the replace method.

2. Annoying, the dynamic input content is uncontrollable. If there are special characters, they need to be escaped, otherwise there will be problems as the parameters of RegExp.

Fortunately, now with the replaceAll method, you can easily replace all matching strings, as simple as explosion +1.

 name = name.replaceAll('xin', '<mark>xin</mark>');

Second, the syntax and details of replaceAll

grammar

replaceAll syntax is the same as replace , and supports string replacement or regular replacement:

 replaceAll(pattern, replacement)

But there are some differences in specific details.

detail

First of all, the regular expression in replaceAll must have the global identifier ‘g’, otherwise an error will be reported.

For example, the following JS execution will report an error:

 'hello world'.replaceAll(/\s/, ''); // will report an error

Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument

error message

Secondly, like the replace method, replaceAll can also match and replace even empty strings, for example:

 'Zhang Xinxu'.replaceAll('', '_')

The result returned is: ‘_zhang_xin_xu_’

As shown in the screenshot below:

Empty string replacement

Therefore, when implementing search highlight matching, if it is an empty string, it is necessary not to perform the matching operation, otherwise many unexpected <mark> elements will be inserted.

compatibility

IE browser does not support it, other browsers already support it, as shown in the following figure:

replaceAllCompatibility

Third, let’s talk about matchAll

matchAll method has only been supported in the last three years, which is a year and a half earlier than the replaceAll method.

Compared with the match method, the return value of matchAll includes not only the matched content, but also the matched group (that is, the part enclosed in parentheses in the regular expression).

Below is an example to show the difference between the two.

 let str = 'author\'s name is zxx'; const reg = /\s+([az]+)/g;  console.log(str.match(reg)); console.log(str.matchAll(reg));

The return values ​​of the two are:

 The match method returns: ['name', 'is', 'zxx'] matchAll returns: RegExpStringIterator, after converting to an array, the value is:  [Array(2), Array(2), Array(2)] 0: (2) [' name', 'name', index: 8, input: "author's name is zxx", groups: undefined] 1: (2) ['is', 'is', index: 13, input: "author's name is zxx", groups: undefined] 2: (2) [' zxx', 'zxx', index: 16, input: "author's name is zxx", groups: undefined] length: 3

The result after execution in the Chrome console panel is as follows:

matchAll screenshot

It can be seen that the grouping ignored by the match method directly returns the matching array content, and the array items in the iterator returned by matchAll contain the content captured by the grouping. In terms of function, it is somewhat similar to regexp.exec() method. (The same is true for the return value of an array item).

However, there are still differences in details. The regularity of matchAll is a one-shot deal, and reg.lastIndex is fixed. It is not possible to modify the lastIndex to make the regular expression move forward or backward like regexp.exec() .

syntax and details

The syntax is as follows:

 matchAll(regexp)

Among them, regexp represents a regular expression, which must have the ‘g’ global identifier, otherwise an error will be reported, which is consistent with the replaceAll method.

When there is no match, the match method returns null , and matchAll returns an iterable iterator. After the array is converted, it is an empty array, which is the same as the data type at the time of matching. Therefore, in practice, JS execution error probability To be smaller (for newcomers).

compatibility

Look directly at the picture, full of greenery:

matchAll green

Fourth, the conclusion

Since matchAll can only deal with regular expressions, the spread and usage rate of matchAll in JS code must be less than replaceAll , because regular expressions are the soft underbelly of many developers.

This is obviously not a long-term solution. Regular expressions must be studied carefully and practiced repeatedly, until you can reach the state where you can write complex regular expressions by yourself.

There is a saying that you can use regular expressions wherever you need to process strings. If regular expressions don’t work, write another regular expression.

Okay, that’s all.

Recently, there is an urgent project, and I have a lot of overtime. At the same time, I am catching up with the manuscript of “CSS Selector World”, and I have a lot of fishing on weekends, so the update of the article is delayed, and it will be made up this week.

Oh, aha, remember to like and share!

2764.svg

This article is an original article, welcome to share, do not reprint in full text, if you really like it, you can collect it, it will never expire, and will update knowledge points and correct errors in time, and the reading experience will be better.

The address of this article: https://www.zhangxinxu.com/wordpress/?p=10499

(End of this article)

This article is reprinted from: https://www.zhangxinxu.com/wordpress/2022/08/js-replaceall-matchall/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment