标签:app 相同 text while 接下来 查询 ext 使用 扫描
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 14 // 这是结果
15 data = array.join("") + remaining;
接着,再进一步,实现使用正则表达式来进行全局替换,大致思路是先找到正则匹配项,放入一个数组,在循环遍历每一项,使用上面的方法进行全局替换。
要注意的是,替换的数组不能有重复项,否则有可能出现问题,比如我想把 old 替换成 older,如果有两个 old 在数组中,最后的结果就会变成 olderer 。
1 /**
2 * 字符串的全局替换
3 * @param oldText {string} 原始字符串
4 * @param searchValue {string} 需要替换的字符串
5 * @param replaceValue {string} 替换后的字符串
6 * @returns {string} 返回结果
7 */
8 function replaceAll(oldText, searchValue, replaceValue) {
9 let result = oldText;
10 // 检查是否是正则表达式
11 // 如果是正则表达式,则获得匹配内容
12 let search;
13 if (searchValue) {
14 // 首先去掉空格
15 search = searchValue.match(/S+/g)[0];
16 // 匹配以 / 符号开头 以 /img 形式结尾的内容
17 search = search.search(/^/[sS]*?/[img]$/g);
18 } else {
19 search = -1;
20 }
21 // 为了方便直接创建一个数组用来存放需要替换的值
22 let searchArray = [];
23 if (search !== -1) {
24 let pattern = searchValue.slice(searchValue.indexOf("/") + 1, searchValue.lastIndexOf("/"));
25 let modifiers = searchValue.slice(searchValue.lastIndexOf("/") + 1, searchValue.length);
26 // 防止正则写的有问题,或者只是写的像正则实际不是而导致的 nothing to repeat 报错。
27 try {
28 search = oldText.match(new RegExp(pattern, modifiers));
29 } catch (e) {
30 console.log(e);
31 // 报错则默认为是需要替换的文本
32 search = null;
33 searchArray.push(searchValue);
34 }
35 if (search !== null) {
36 // 匹配成功后去掉重复项
37 search.forEach(function (item1) {
38 // if(searchArray.includes(item1)){}
39 // IE 不支持 array.includes() 所以自己写一个循环吧
40 // 数组中有相同元素则为 true
41 let alreadyIn = false;
42 searchArray.forEach(function (item2) {
43 if (item1 === item2) {
44 alreadyIn = true;
45 }
46 });
47 if (!alreadyIn) {
48 searchArray.push(item1);
49 }
50 });
51 } else {
52 // 匹配失败也默认为是需要替换的文本
53 searchArray.push(searchValue);
54 }
55 } else {
56 // 不是正则表达式也需要添加进数组
57 searchArray.push(searchValue);
58 }
59 // 来循环吧,把 search 里的每个元素换一遍,当然首先里面要有元素
60 if (searchValue) {
61 let remaining = result;
62 searchArray.forEach(function (item) {
63 // 将上一次替换结束的字符串赋值给未扫描的字符串变量
64 remaining = result;
65 let array = [];
66 let start = remaining.indexOf(item);
67 console.log(start);
68 // 没有匹配项则返回源字符串
69 if (start === -1) {
70 result = remaining;
71 }
72 while (start !== -1) {
73 let end = start + item.length;
74 array.push(remaining.slice(0, start));
75 array.push(replaceValue);
76 remaining = remaining.slice(end, remaining.length);
77 start = remaining.indexOf(item);
78 result = array.join("") + remaining;
79 }
80 });
81 }
82 return result;
83 }
JavaScript 自己写一个 replaceAll() 函数
标签:app 相同 text while 接下来 查询 ext 使用 扫描
原文地址:https://www.cnblogs.com/roak/p/12411295.html