当前位置: 首页 > news >正文

js 实现replaceAll

为什么80%的码农都做不了架构师?>>>   hot3.png

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:用于替换的子字符串。


转载于:https://my.oschina.net/muziH/blog/313406

相关文章:

  • 性能测试结果分析(中级测试)
  • C++ 多线程入门1
  • OSGi Event Admin Service
  • jQuery ajax - post() 方法
  • 软件培训
  • 如何优化Mysql千万级快速分页
  • MySQL InnoDB体系结构
  • C++ 小复习
  • 在Linux中让echo命令显示带颜色的字
  • ORACLE用户操作的一些常用操作总结【weber出品】
  • QuiltView 瀑布流 (第三方)
  • nginx源码编译
  • varnish代理缓存讲解
  • 泛型排序器 TComparer
  • WinAPI: ShellExecute - 打开外部程序或文件
  • 2018一半小结一波
  • go语言学习初探(一)
  • IndexedDB
  • JavaScript学习总结——原型
  • Kibana配置logstash,报表一体化
  • October CMS - 快速入门 9 Images And Galleries
  • react 代码优化(一) ——事件处理
  • React+TypeScript入门
  • spring boot下thymeleaf全局静态变量配置
  • Vue学习第二天
  • 如何解决微信端直接跳WAP端
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • 在weex里面使用chart图表
  • 2017年360最后一道编程题
  • #include<初见C语言之指针(5)>
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • $.ajax,axios,fetch三种ajax请求的区别
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (floyd+补集) poj 3275
  • (Oracle)SQL优化技巧(一):分页查询
  • (ZT) 理解系统底层的概念是多么重要(by趋势科技邹飞)
  • (超详细)语音信号处理之特征提取
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (十二)python网络爬虫(理论+实战)——实战:使用BeautfulSoup解析baidu热搜新闻数据
  • (一)WLAN定义和基本架构转
  • (原创)Stanford Machine Learning (by Andrew NG) --- (week 9) Anomaly DetectionRecommender Systems...
  • (转)编辑寄语:因为爱心,所以美丽
  • (转)重识new
  • (轉貼) UML中文FAQ (OO) (UML)
  • (总结)Linux下的暴力密码在线破解工具Hydra详解
  • .apk 成为历史!
  • .Net - 类的介绍
  • .net CHARTING图表控件下载地址
  • .NET Compact Framework 多线程环境下的UI异步刷新
  • @converter 只能用mysql吗_python-MySQLConverter对象没有mysql-connector属性’...
  • @entity 不限字节长度的类型_一文读懂Redis常见对象类型的底层数据结构
  • @serverendpoint注解_SpringBoot 使用WebSocket打造在线聊天室(基于注解)
  • @软考考生,这份软考高分攻略你须知道
  • [2021]Zookeeper getAcl命令未授权访问漏洞概述与解决
  • [Android 数据通信] android cmwap接入点