Home  >  Article  >  Web Front-end  >  JavaScript string object replace method instance (for string replacement or regular replacement)_Basic knowledge

JavaScript string object replace method instance (for string replacement or regular replacement)_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:33:411623browse

JavaScript replace method

The

replace 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:

Copy code The code is as follows:

str_object.replace(reg_exp/str, replacement)

Parameter description:

Parameters Description
str_object String (object) to be operated on
reg_exp/str Required. Regular expression to match/String to replace
参数 说明
str_object 要操作的字符串(对象)
reg_exp/str 必需。要匹配的正则表达式/要替换的字符串
如果 reg_exp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。
replacement 必需。要替换的字符串
If reg_exp has the global flag g, then the replace() method will replace all matching substrings. Otherwise, it only replaces the first matching substring.
replacement Required. String to replace

String replacement example

The following example demonstrates a string replacement instance of the replace method:

Copy code The code is as follows:


Run this example, output:

Copy code The code is as follows:

www.jb51.net

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, the

replace method also supports regular expression replacement:

Copy code The code is as follows:


Run this example, output:

Copy code The code is as follows:

www.jb51.net is an example domains site of INNA.

When adding the global flag g to the regular expression:

Copy code The code is as follows:


Run this example, output:

Copy code The code is as follows:

www.jb51.net is a 5idev domains site of INNA.

Note that if you want to ignore case, you can add the i parameter: /example/gi .

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn