String.prototype.replace--替换字符串
str.replace(regexp|substr, newSubStr|function)
API本身不改变原本的字符串,只是返回新的字符串
例子:用函数作为第二个参数
function replacer(match, p1, p2, p3, offset, string, namedCaptureGroup) {
console.log('match', match) // abc12345#$*%
console.log('p1, p2, p3', p1, p2, p3) // abc 12345 #$*%
console.log('string', string) // abc12345#$*%
// match 与 string 刚好相同,只是因为match都匹配上了
return [p1, p2, p3].join(' - ')
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%
函数的参数分别有:
1. match: 匹配的字串
2. p1,p2,p3...:例如:/(\a+)(\b+)/, p1 ---> \a+; p2 ---> \b+
3. offset: 匹配到的子字符串在原字符串中的偏移量;(比如:原字符串是“abcd”,匹配到的字符串是“bc”,那么这个参数将会是1)
4. 被匹配的原字符串
例子:用字符串做第二个参数
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
// oranges are round, and oranges are juicy.
console.log(newstr);
例子:用特殊字符串做第二参数
"$$": "$"
"$&": 插入匹配的字串
"$`": 插入当前匹配的子串左边的内容。
"$'": 插入当前匹配的子串右边的内容。
"$n": $1, $2, $3
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
// Smith, John
console.log(newstr);
最新文章
- RabbitMQ消息队列1: Detailed Introduction 详细介绍
- 服务器程序DEBUG
- hiho #1223 不等式
- Hibernate-一对多的关系维护
- mongodb用户授权
- 获取当前页面的完整URL
- MyEclipse开发的java web项目在 Eclipse中无法识别
- UVA 1660 Cable TV Network
- LearningDocker--Chapter3--Building images
- 一步步学习EF Core(1.DBFirst)
- MySQL 开发实践
- 腾讯基于Kubernetes的企业级容器云平台GaiaStack (转)
- 3 并发编程-(进程)-join方法
- 【cs231n】卷积神经网络
- Python实现常见算法[2]——快速排序
- 《梦断代码Dreaming In Code》阅读计划
- 第一章 安装MongoDB
- freemarker macro 使用
- IP头,TCP头,UDP头,MAC帧头定义
- andriod 支付宝类似界面图片加文字