This article mainly introduces 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, I hope it can help everyone.
1. Match method
The match() method can retrieve a specified value within a 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
The replace() method is used to replace some characters with other characters in a string, or replace a substring that matches a 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 all strings can be matched or replaced.
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:
Related recommendations:
match with Detailed explanation of the replace method
The functions of substr() and match() in js
Change the image and use the example code of the match method
The above is the detailed content of Detailed explanation of match and replace examples of strings in JavaScript. For more information, please follow other related articles on the PHP Chinese website!