Regex - effectively use all the shortcuts from this list in the text

I have a list of shortcuts:

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

and the text of the text of various capitalization:

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

Is it possible to replace all words in the text corresponding to the list of labels with the title version of the label using a regular expression? Is it possible to do this without a loop with just String.prototype.replace () ?

The desired result in my example:

 myText = "Lorem ipsum... EFA, EFA, EFA ..."; 
+6
source share
3 answers

Create a single regular expression with an array of strings and replace the string using the 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

+6
source

Assuming you control the original array of shortcuts, and know that it contains only 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())); 

Borders \b will not replace labels inside words.

+2
source

simple approach without 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); 
0
source

Source: https://habr.com/ru/post/1014258/


All Articles