javascript中使用replaceAll()函数实现字符替换的方法
作者:mdxy-dxy 时间:2024-04-10 16:18:47
而str.replace(/\-/g,"!")则可以全部替换掉匹配的字符(g为全局标志)。
replace()
The replace() method returns the string that results when you replace text matching its first argument
(a regular expression) with the text of the second argument (a string).
If the g (global) flag is not set in the regular expression declaration, this method replaces only the first
occurrence of the pattern. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(/\./, "!" ); // replace first period with an exclamation pointalert(s);
produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(/\./g, "!" ); // replace all periods with exclamation pointsalert(s);
yields this result: “Hello! Regexps are fun!”
所以可以用以下几种方式.:
string.replace(/reallyDo/g, replaceWith);
string.replace(new RegExp(reallyDo, 'g'), replaceWith);
string:字符串表达式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替换的子字符串。
<script type="text/javascript">
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);
} else {
return this.replace(reallyDo, replaceWith);
}
}
</script>
补充
我们在Java中可以使用replaceAll()方法对字符串进行批量替换,但在JS中replaceAll()方法是undefined,JS中只存在replace()方法,因此我们可以自己封装JS中replaceAll()方法供我们便捷使用。
一、使用replace()方法进行替换
定义一个字符串:
var str = "hello world";
使用replace()方法将字符串中的字母"l"替换成"i",原始做法:
console.log(str.replace("l","i"));
输出:
“heilo world”
需要执行三次,非常不方便;
二、使用replaceAll()方法替换
封装replaceAll()方法:
String.prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2);
}
定义一个字符串:
var str = "hello world";
使用replaceAll()方法进行批量替换:
console.log(str.replaceAll("l", "i"));
输出:
“heiio worid”
只需要执行一次,就完成了全部替换需求。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 下载文件的多种方法汇总
![](https://img.aspxhome.com/file/2023/7/105017_0s.gif)
mysql数据库下损坏数据的恢复操作其过程总结
如何使用json在前后台进行数据传输实例介绍
SQL Server 2008 清空删除日志文件(瞬间日志变几M)
struts2.3.24+spring4.1.6+hibernate4.3.11+mysql5.5.25开发环境搭建图文教程
![](https://img.aspxhome.com/file/2023/5/68735_0s.jpg)
一文带你了解ChatGPT API的使用
![](https://img.aspxhome.com/file/2023/4/131924_0s.png)
Python简易版图书管理系统
使用python打印十行杨辉三角过程详解
![](https://img.aspxhome.com/file/2023/1/103201_0s.png)
MySQL中字符串与Num类型拼接报错的解决方法
oracle group by语句实例测试
总结Python连接CS2000的详细步骤
![](https://img.aspxhome.com/file/2023/7/70197_0s.png)
php7性能提升的原因详解
python3 判断列表是一个空列表的方法
Python K最近邻从原理到实现的方法
![](https://img.aspxhome.com/file/2023/0/90770_0s.png)
解决Python 命令行执行脚本时,提示导入的包找不到的问题
![](https://img.aspxhome.com/file/2023/1/105341_0s.jpg)
XML与HTML的结合(上)
浅谈Python 递归算法指归
![](https://img.aspxhome.com/file/2023/5/133395_0s.png)
使用XML技术上传文件的例子
对python生成业务报表的实例详解
![](https://img.aspxhome.com/file/2023/3/120453_0s.jpg)