Home > Web Front-end > JS Tutorial > How to use replace method

How to use replace method

不言
Release: 2019-01-28 13:54:52
Original
35851 people have browsed it

replace方法可以查找正则表达式和字符串之间的匹配项,并使用新的子字符串替换匹配的子字符串,本篇文章我们就来看一下replace方法的具体用法。

How to use replace method

首先我们来看一下replace方法的基本语法

1

string.replace(regexp/substr, newSubStr/function[, flags]);

Copy after login

regexp - 一个RegExp对象。

substr - 要由newSubStr替换的String。

newSubStr - 替换从参数接收的子字符串的String。

function - 要调用以创建新子字符串的函数。

flags - 包含RegExp标志的任意组合的String:g - 全局匹配,i - 忽略大小写,m - 匹配多行。仅当第一个参数是字符串时才使用此参数。

接下来我们来看具体的示例

替换字符串

代码如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title></title>

</head>

<body>

 <script type = "text/javascript">

        var string = "This is a pig!";

        var result = string.replace("pig", "Dog");

        document.write(result);

      </script>      

</body>

</html>

Copy after login

浏览器上输出结果如下:

How to use replace method

替换正则表达式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title></title>

</head>

<body>

 <script type = "text/javascript">

        var re = /(\w+)\s(\w+)/;

         var str = "zara ali";

         var newstr = str.replace(re, "$2, $1");

         document.write(newstr);

      </script>      

</body>

</html>

Copy after login

浏览器上显示效果如下

How to use replace method

本篇文章到这里就全部结束了,更多精彩内容大家可以关注php中文网的相关栏目教程!!!

The above is the detailed content of How to use replace method. 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