Home > Web Front-end > JS Tutorial > body text

Detailed explanation of match and replace examples of strings in JavaScript

小云云
Release: 2018-01-05 10:22:15
Original
1337 people have browsed it

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!