Home  >  Article  >  Web Front-end  >  How to use replace method

How to use replace method

不言
不言Original
2019-01-28 13:54:5235827browse

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

How to use replace method

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

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

regexp - 一个RegExp对象。

substr - 要由newSubStr替换的String。

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

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

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

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

替换字符串

代码如下

<!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>

浏览器上输出结果如下:

How to use replace method

替换正则表达式

<!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>

浏览器上显示效果如下

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!

Statement:
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