JavaScript 自己写一个 replaceAll() 函数

JavaScript 的  replace()  方法可以在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

但是,只输入字符串的话,仅替换第一个字符,当然也可以用正则表达式来进行全局替换:

1 // 查找所有 word 替换成 words
2 string.replace(/word/g,"words");

那么,问题来了,如果我用的是变量呢?百度到可以这么来:

1 // 随便来一条字符串
2 let str = "How old are you? Yes, I'm very old!"
3 let search = "old";
4 // 使用 new RegExp(pattern,modifiers) 创建正则表达式
5 let pattern = new RegExp(search, "g");
6 let str = text.value.replace(pattern, "young");
7 // 结果:How young are you? Yes, I'm very young!

但是,不用 new RegExp 自己写一个函数,要怎么实现呢(我果然是太闲了)?

首先,摒弃掉 replace() 函数,自己来替换。

替换的话,不就是从前往后找想要替换的文并且一个个换掉嘛。

思路是这样的,用 indexOf() 方法返回指定的字符串在字符串中首次出现的位置,并用 slice(start, end)  方法提取找过但没有匹配项的,匹配的文字和还没找的三个部分,将第一部分和替换文字放入数组中,还没找的部分中再次使用这种办法,直至字符串末尾,将数组连起来成为一条字符串就是我想要的结果啦。

这是仅一次替换,咦,这不就是 replace() 嘛:

 1 // 用于存放文字的数组
 2 let array = [];
 3 let data;
 4 // 查询的文字第一次出现的位置
 5 let start = oldText.indexOf(searchValue);
 6 // 没有找到匹配的字符串则返回 -1 
 7 if (start !== -1) {
 8     // 查找的字符串结束的位置
 9     let end = start + searchValue.length;
10     // 添加没有匹配项的字符,即从头到查询的文字第一次出现的位置
11     array.push(oldText.slice(0, start));
12     // 添加替换的文字来代替查询的文字
13     array.push(replaceValue);
14     // 剩下没有查询的文字
15     let remaining = oldText.slice(end, oldText.length);
16     // 这是结果
17     data = array[0] + array[1] + remaining;
18 } else {
19     // 没找到呀
20     data = "No Found" + searchValue + "!";
21 }
22 let textNode = document.createTextNode(data);
23 span.appendChild(textNode);

接下来进行全局替换,使用 while 循环,判定条件就是 indexOf(searchValue) 是否能找到文字,返回 -1 就停止循环。

 1 let array;
 2 // 用于存放未查找的文字
 3 let remaining = oldText;
 4 let data;
 5 let start = oldText.indexOf(searchValue);
 6 while (start !== -1) {
 7     let end = start + searchValue.length;
 8     array.push(remaining.slice(0, start));
 9     array.push(replaceValue);
10     remaining = remaining.slice(end, remaining.length);
11     start = remaining.indexOf(searchValue);
12 }
13 if (array){
14     // 这是结果
15     data = array.join("") + remaining;
16 } else {
17     // 没找到呀
18     data = "No Found " + searchValue + "!";
19 }

猜你喜欢

转载自www.cnblogs.com/jmtm/p/11804608.html