js中string之正则表达式replace方法怎么用
String.prototype.replace()
String.prototype.replace() 是 JavaScript 中一个常用的字符串方法,它的作用是替换字符串中的某一个子串。它接收两个参数,第一个参数可以是一个字符串或者正则表达式,第二个参数是替换的字符串。
1. 使用字符串替换
第一种使用方法是使用字符串替换,例如:
let str = 'hello world';
str = str.replace('world', 'javascript');
console.log(str); // hello javascript输出结果:hello javascript
2. 使用正则表达式替换
第二种使用方法是使用正则表达式替换,例如:
let str = 'hello world';
str = str.replace(/world/, 'javascript');
console.log(str); // hello javascript输出结果:hello javascript
3. 使用函数替换
第三种使用方法是使用函数替换,例如:
let str = 'hello world';
str = str.replace(/world/, function(match) {
return 'javascript';
});
console.log(str); // hello javascript输出结果:hello javascript
总之,String.prototype.replace() 方法可以用来替换字符串中的某一个子串,其可以使用字符串、正则表达式和函数作为参数,从而实现替换的功能。
猜您想看
-
如何解决在CS:GO中启动时出现缺少dll文件的问题?
如何解决CS:...
2023年04月17日 -
Synchronized 与 ReentrantLock 的区别是什么
Synchro...
2023年07月23日 -
如何在 CentOS 7 上安装和配置 OpenLDAP 客户端?
在CentOS...
2023年04月26日 -
如何编译安装php7.3
编译安装PHP...
2023年07月21日 -
用这些网易云音乐小技巧,快速提升你的听歌品质。
一、播放器设置...
2023年05月15日 -
如何解决Hive中decimal类型字段.0结尾数据显示异常问题
问题描述:在H...
2023年07月23日