JavaScript 本身寫一個 replaceAll() 函數

JavaScript 的  replace()  方法能夠在字符串中用一些字符替換另外一些字符,或替換一個與正則表達式匹配的子串。正則表達式

可是,只輸入字符串的話,僅替換第一個字符,固然也能夠用正則表達式來進行全局替換:數組

1 // 查找全部 word 替換成 words
2 string.replace(/word/g,"words");

那麼,問題來了,若是我用的是變量呢?百度到能夠這麼來:app

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() 函數,本身來替換。spa

替換的話,不就是從前日後找想要替換的文而且一個個換掉嘛。code

思路是這樣的,用 indexOf() 方法返回指定的字符串在字符串中首次出現的位置,並用 slice(start, end)  方法提取找過但沒有匹配項的,匹配的文字和還沒找的三個部分,將第一部分和替換文字放入數組中,還沒找的部分中再次使用這種辦法,直至字符串末尾,將數組連起來成爲一條字符串就是我想要的結果啦。blog

這是僅一次替換,咦,這不就是 replace() 嘛:ip

 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 就中止循環。rem

 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(/^\/[\s\S]*?\/[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 }
相關文章
相關標籤/搜索