首页 web前端 js教程 JS中实现replaceAll的方法(实例代码)_javascript技巧

JS中实现replaceAll的方法(实例代码)_javascript技巧

May 16, 2016 pm 05:16 PM
js replaceall方法

第一次发现JavaScript中replace() 方法如果直接用str.replace("-","!") 只会替换第一个匹配的字符.
而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:用于替换的子字符串。

复制代码 代码如下:

 
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热门文章标签

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何使用JS和百度地图实现地图平移功能 如何使用JS和百度地图实现地图平移功能 Nov 21, 2023 am 10:00 AM

如何使用JS和百度地图实现地图平移功能

股票分析必备工具:学习PHP和JS绘制蜡烛图的步骤 股票分析必备工具:学习PHP和JS绘制蜡烛图的步骤 Dec 17, 2023 pm 06:55 PM

股票分析必备工具:学习PHP和JS绘制蜡烛图的步骤

推荐:优秀JS开源人脸检测识别项目 推荐:优秀JS开源人脸检测识别项目 Apr 03, 2024 am 11:55 AM

推荐:优秀JS开源人脸检测识别项目

PHP与JS开发技巧:掌握绘制股票蜡烛图的方法 PHP与JS开发技巧:掌握绘制股票蜡烛图的方法 Dec 18, 2023 pm 03:39 PM

PHP与JS开发技巧:掌握绘制股票蜡烛图的方法

如何使用PHP和JS创建股票蜡烛图 如何使用PHP和JS创建股票蜡烛图 Dec 17, 2023 am 08:08 AM

如何使用PHP和JS创建股票蜡烛图

如何使用JS和百度地图实现地图多边形绘制功能 如何使用JS和百度地图实现地图多边形绘制功能 Nov 21, 2023 am 10:53 AM

如何使用JS和百度地图实现地图多边形绘制功能

如何使用JS和百度地图实现地图点击事件处理功能 如何使用JS和百度地图实现地图点击事件处理功能 Nov 21, 2023 am 11:11 AM

如何使用JS和百度地图实现地图点击事件处理功能

如何使用JS和百度地图实现地图热力图功能 如何使用JS和百度地图实现地图热力图功能 Nov 21, 2023 am 09:33 AM

如何使用JS和百度地图实现地图热力图功能

See all articles