当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript 自己写一个 replaceAll() 函数

JavaScript 自己写一个 replaceAll() 函数

2019年11月06日  | 移动技术网IT编程  | 我要评论

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 }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网