regex - efficiently capitalize all shortcuts from given list in a text
我有一个快捷方式列表:
1 | var shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"... |
以及各种资本化的正文:
1 | var myText ="Lorem ipsum... Efa, efa, EFA ..."; |
是否可以使用regex将文本中与快捷方式列表匹配的所有单词替换为快捷方式的大写版本?如果不使用string.prototype.replace()循环,是否可以这样做?
在我的例子中,期望的结果是:
1 | myText ="Lorem ipsum... EFA, EFA, EFA ..."; |
使用字符串数组生成单个regex,并使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | var shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"]; var myText ="Lorem ipsum... Efa, efa, EFA ..."; // construct the regex from the string var regex = new RegExp( shortcuts // iterate over the array and escape any symbol // which has special meaning in regex, // this is an optional part only need to use if string cotains any of such character .map(function(v) { // use word boundary in order to match exact word and to avoid substring within a word return '\\b' + v.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + '\\b'; }) // or you can use word boundary commonly by grouping them // '\\b(?:' + shortcuts.map(...).join('|') + ')\\b' // join them using pipe symbol(or) although add global(g) // ignore case(i) modifiers .join('|'), 'gi'); console.log( // replace the string with capitalized text myText.replace(regex, function(m) { // capitalize the string return m.toUpperCase(); }) // or with ES6 arrow function // .replace(regex, m => m.toUpperCase()) ); |
引用:将用户输入字符串转换为正则表达式
假设您控制了初始快捷方式数组,并且您知道它只包含字符:
1 2 3 4 5 6 7 | const shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"] var text ="Lorem ipsum... Efa, efa, EFA, ame, America, enamel, name ..." var regex = new RegExp("\\b(" + shortcuts.join('|') +")\\b", 'gi') console.log(text.replace(regex, s => s.toUpperCase())); |
不带
1 2 3 4 5 | var shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"], myText ="Lorem ipsum... Efa, efa, EFA ..aps apS whatever APS."; shortcuts.map((el)=> { myText = myText.replace(new RegExp('\\b'+el+'\\b',"gi"), el.toUpperCase()) }); console.log(myText); |