Extending String prototype with useful methods

JavaScript’s String primitive has a wide variety of methods that manipulate internal state and provide different ways to interface it to your functionality. String helper methods could be extended by creating custom functions that could be used the same way default methods are invoked.
A simple case could be a scenario when you want to use a ‘templating’ functionality without actually relying on third party libraries. The task could be done by just few lines of code like the example below:

/**
 * Implementation of string 'replaceTokens'
 *
 * @remark - replaces all tokens in the form of {x}, {y}, {z}, etc... by the passed map parameters
 *
 * const test = 'Both numbers {one} and {two} are not equal';
 * const map = { one: 1, two: 2 };
 * console.log(test.replaceTokens(map));
 * ---> 'Both numbers 1 and 2 are not equal'
 */
String.prototype.replaceTokens = function() {
  let sourceString = this;
  const [map] = arguments;

  sourceString.replace(/\{(.*?)}/g, function(token, key) {
    sourceString = sourceString.replace(token, map[key]);
  });

  return sourceString;
};

If you are coding it in TypeScript you will probably notice the Property ‘replaceTokens’ does not exist on type ‘String’ error. It’s related to the fact that you are trying to ‘extend’ the String primitive with something that has not been defined yet. The way to resolve the issue is to for example create a string.d.ts file holding the next declaration:

declare interface String {
    replaceTokens: Function;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.