Home > Article > Web Front-end > About match and replace methods in JavaScript (detailed tutorial)
The editor below will introduce to you the match and replace methods of strings in JavaScript. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look.
1. Match method
The match() method can retrieve the specified value within the string. Or find a match for one or more regular expressions.
The return value of the match() method is: an array storing the matching results.
2. Replace method
Thereplace() method is used to replace some characters with other characters in a string, or replace an The substring matched by the regular expression.
The return value of the replace method is: a new string.
3. Description
#The parameters of the above two methods mainly add global g when using regular expressions, so that the string can be processed Match or replace all.
Sample code:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>JavaScript中字符串的match与replace方法</title> </head> <body> <!--注意src路径要对--> <script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> var str = "1 plus 2 equal 3"; //match方法返回值为数组 var arr = str.match(/[0-9]/g) console.log(arr); var new_str = str.replace(/[0-9]/g, 'newstr'); //replace方法返回值为新的字符串 console.log(new_str) </script> </body> </html>
The console output is:
The above is I compiled it for everyone, I hope it will be helpful to everyone in the future.
Related articles:
How to use vue to implement login registration and token verification
How to use Javascript to implement a custom event mechanism
Detailed interpretation of the map data structure in javascript
How to develop a two-dimensional weekly view calendar using Javascript
The above is the detailed content of About match and replace methods in JavaScript (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!