JavaScript's method of string translation conversion through dictionaries

  • 2020-05-17 04:46:32
  • OfStack

The example in this article describes the method of string translation conversion by JavaScript through a dictionary. Share with you for your reference. The specific analysis is as follows:

In this case, we actually set up a dictionary for comparison, and then find the corresponding key value from the dictionary through the translation function. You need to use JavaScript version 1.8 or above

The function definition is as follows:


function CreateTranslator(translationTable)
function(s) s.replace(
new RegExp([k for (k in translationTable)].join('|'), 'g'),
function(str) translationTable[str]
);

Call method:


var translationTable = { a:1, bb:2, b:3, c:4 };
var MyTranslater = CreateTranslator( translationTable );
MyTranslater('aabbbc'); // returns: 11234

I hope this article has been helpful to your javascript programming.


Related articles: