我有一个快捷键列表:
var shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"...
以及各种大写文本:
var myText = "Lorem ipsum... Efa, efa, EFA ...";
是否可以使用正则表达式将快捷方式列表中的所有单词替换为快捷方式的大写版本?是否可以在没有循环的情况下使用 String.prototype.replace()来做到这一点?
我的例子中的预期结果是:
myText = "Lorem ipsum... EFA, EFA, EFA ...";
答案 0 :(得分:6)
使用字符串数组生成单个正则表达式,并使用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())
);

答案 1 :(得分:2)
假设您控制了初始快捷方式数组,并且您知道它只包含字符:
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()));

\b
边界将避免替换单词内的快捷方式。
答案 2 :(得分:0)
没有join
的简单方法:
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);