第一次发现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:用于替换的子字符串。
js代码
0
0
相关文章
为什么学习javascript_能提升你的职业竞争力吗
如何让 HTML 页面正确调用并执行 JavaScript 函数
Rails 7 中非模块化第三方 JS 库的正确集成方案
Rails 7 中非模块化第三方 JS 库的正确引入方式
Rails 7 中非模块化第三方 JS 库的正确集成方式
相关标签:
本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门AI工具
相关专题
Java 桌面应用开发(JavaFX 实战)
本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。
61
2026.01.14
热门下载
相关下载
精品课程
相关推荐
/
热门推荐
/
最新课程
前端项目-尚优选【HTML/CSS/JS技术综合实战】
共39课时 | 4万人学习
WEB前端教程【HTML5+CSS3+JS】
共101课时 | 8.3万人学习
JS进阶与BootStrap学习
共39课时 | 3.2万人学习
最新文章









