Regular expression syntax based on replace function in JavaScript

Time:2021-2-13

The sample code is as follows:


[Ctrl + a all optional note: to introduce external JS, you need to refresh the page again]

It just replaces the initials. But if you add regular expressions, the result is different! Replace () supports regular expressions. It can match characters or strings according to the rules of regular expressions, and then replace them!

Note: do not use double quotation marks on the replaced part


[Ctrl + a all optional note: to introduce external JS, you need to refresh the page again]

This way, only the first letter A is replaced.


[Ctrl + a all optional note: to introduce external JS, you need to refresh the page again]

From the above, when the regular expression has a “g” flag, it means that the whole string will be processed


[Ctrl + a all optional note: to introduce external JS, you need to refresh the page again]

Let’s start with a simple example: capitalize all words.


[Ctrl + a all optional note: to introduce external JS, you need to refresh the page again]

It can be seen from the above that when the regular expression is marked with “g”, it means that the whole string will be processed, that is, the transformation of function change will be applied to all matching objects. The function has three or more parameters, depending on the regular expression.

With the combination of function and regular expression, the function of replace () to deal with string is more powerful than ever!

Finally, an example is given to show how easy it is to reverse the order of all the words in a string and use replace() to process them.


[Ctrl + a all optional note: to introduce external JS, you need to refresh the page again]

For those who are not familiar with regular expressions, please refer to the following article
Regular expression 30 minutes tutorial
Basic information of regular expression