SoFunction
Updated on 2025-02-28

Regular expression syntax based on replace function in javascript

The sample code is as follows:

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

It only replaces the initials. But if you add regular expressions, the result will be different! replace() supports regular expressions, which can match characters or strings according to the rules of regular expressions and then give a replacement!

Note: The replaced part does not need to be double quoted.

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

This way, only the first letter a is replaced.

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

From the above, we can see that when the regular expression has the "g" flag, it means that the entire string will be processed.

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

Let’s take a look at a simple example: Change the initial letter of all words to capitalize.

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

From the above, it can be seen that when the regular expression has the "g" flag, it means that the entire string will be processed, that is, the transformation of the function change will be applied to all matching objects. The function has three or more parameters, and the specific number depends on the regular expression.

With the combination of functions and regular expressions, the function of replace() to process strings has become unprecedentedly powerful!

Finally, let’s give an example, it is so simple to use replace() to process all words in reverse order.

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

Friends who are not familiar with regular expressions can refer to the following article
30-minute tutorial on getting started with regular expressions
Regular expressions Basic information