javascript中replace的基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lqlqlq007/article/details/79338503

replace方法的定义戳这里

下面给出几种基本用法的例子:

  1. 替换唯一字符串(极少用到):
let test = "123liqing1234";
let result = test.replace("liqing", "test");
console.log("result is " + result);

执行结果:
这里写图片描述
2. 批量替换字符串(因为javascript并不提供replaceAll方法,所以需要我们自己用正则来实现):

let test = "123liqing1234liqing123";
let result = test.replace(/liqing/g, "test");
console.log("result is " + result);

执行结果:
这里写图片描述
3. 批量替换字符串时需要执行额外的处理逻辑:

let test = "123liqing1234li5qing123";
let result = test.replace(/li[0-9]?qing/g, str => str.length < 7 ? "testA" : "testB");
console.log("result is " + result);

执行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/lqlqlq007/article/details/79338503