我有一个快捷方式列表:
var shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"...
Run Code Online (Sandbox Code Playgroud)
以及各种大写文本:
var myText = "Lorem ipsum... Efa, efa, EFA ...";
Run Code Online (Sandbox Code Playgroud)
是否可以使用正则表达式将快捷方式列表中的所有单词替换为快捷方式的大写版本?是否可以在没有循环的情况下使用String.prototype.replace()来做到这一点?
我的例子中期望的结果是:
myText = "Lorem ipsum... EFA, EFA, EFA ...";
Run Code Online (Sandbox Code Playgroud)
使用string数组生成单个正则表达式,并使用String#replace
带回调的方法替换字符串.
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())
);
Run Code Online (Sandbox Code Playgroud)
请参阅:将用户输入字符串转换为正则表达式