7

I have a list of shortcuts:

var shortcuts = ["efa","ame","ict","del","aps","lfb","bis","bbc"...

and a body of text of various capitalisation:

var myText = "Lorem ipsum... Efa, efa, EFA ...";

Is it possible to replace all the words in the text that match the shortcut list with a capitalised version of the shortcut using regex? Is it possible to do that without a loop only using String.prototype.replace()?

The desired outcome in my example would be:

myText = "Lorem ipsum... EFA, EFA, EFA ...";
daniel.sedlacek
  • 8,129
  • 9
  • 46
  • 77

3 Answers3

6

Generate a single regex with the array of string and replace the string using String#replace method with a callback.

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())
);

Refer : Converting user input string to regular expression

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

Assuming you control the initial shortcuts array and you know that it only contains characters:

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()));

The \b boundaries will avoid replacing the shortcuts inside words.

Jozef Legény
  • 1,157
  • 1
  • 11
  • 26
0

a simple approach with no 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);
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43