


JavaScript string object replace method instance (for string replacement or regular replacement)_Basic knowledge
May 16, 2016 pm 04:33 PMJavaScript 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:
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
|
||||||||
replacement | Required. String to replace |
String replacement example
The following example demonstrates a string replacement instance of the replace method:
<script language="JavaScript">
var str = "www.example.net";
document.write( str.replace("example", "jb51") );
</script>
Run this example, output:
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, thereplace method also supports regular expression replacement:
<script language="JavaScript">
var str = "www.example.net is an example domains site of INNA.";
document.write( str.replace(/example/, "jb51") );
</script>
Run this example, output:
www.jb51.net is an example domains site of INNA.
When adding the global flag g to the regular expression:
<script language="JavaScript">
var str = "www.example.net is an example domains site of INNA.";
document.write( str.replace(/example/g, "jb51") );
</script>
Run this example, output:
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 .

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement an online speech recognition system using WebSocket and JavaScript

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems

How to implement an online reservation system using WebSocket and JavaScript

How to use JavaScript and WebSocket to implement a real-time online ordering system

JavaScript and WebSocket: Building an efficient real-time weather forecasting system

Simple JavaScript Tutorial: How to Get HTTP Status Code

How to get HTTP status code in JavaScript the easy way

How to use insertBefore in javascript
