Home > Article > Web Front-end > JavaScript string object replace method instance (for string replacement or regular replacement)_Basic knowledge
JavaScript replace method
Thereplace method is used to replace some strings with other strings in a string, or replace strings that match regular matches, and return the replaced string. Its syntax is as follows:
Parameter description:
Parameters | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
str_object | String (object) to be operated on | ||||||||
reg_exp/str | Required. Regular expression to match/String to replace
|
||||||||
replacement | Required. String to replace |
String replacement example
The following example demonstrates a string replacement instance of the replace method:
Run this example, output:
Note: String replacement only replaces the first string that meets the requirements (replaces only once). If you want to replace all strings that meet the requirements in the string, it is recommended to use a regular expression pattern with the global parameter g, specifically See example below.
Regular expression string replacement example
In addition to simple string replacement, thereplace method also supports regular expression replacement:
Run this example, output:
When adding the global flag g to the regular expression:
Run this example, output:
Note that if you want to ignore case, you can add the i parameter: /example/gi .