replace方法可以查找正则表达式和字符串之间的匹配项,并使用新的子字符串替换匹配的子字符串,本篇文章我们就来看一下replace方法的具体用法。 
首先我们来看一下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> 浏览器上输出结果如下: 
替换正则表达式 <!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> 浏览器上显示效果如下 
本篇文章到这里就全部结束了,更多精彩内容大家可以关注模板之家(www.mb5.com.cn)的相关栏目教程!!! 以上就是replace方法怎么使用的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |