In this article, we will introduce you to the match and replace methods of strings in JavaScript. It has a good reference value and we hope it will be helpful to you.
1. Match method
The match() method can retrieve a specified value within a string, or find one or more regular expressions formula matching.
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 content is the match and replace methods of strings in JavaScript (detailed explanation). This is all the content shared by the editor. I hope it can help you. Related recommendations:The functions of substr() and match() in js
js regular search match() and replacement replace() usage example
Usage example of replace() method in Javascript
The above is the detailed content of Detailed explanation of match and replace methods. For more information, please follow other related articles on the PHP Chinese website!