Javascript String format(object)

Description

Javascript String format(object)


/**// w  w w . j a  v  a2s  . c  o m
 * Parse a text with a placeholder object
 * @param object
 * @returns {String}
 */
String.prototype.format = function format(object) {
  let parsed = this;

  Object.keys(object).forEach(option => {
    const regex = new RegExp(`#{${option}}`, 'g');
    parsed = parsed.replace(regex, object[option]);
  });

  return parsed;
};

export default String.prototype.format;

Javascript String format(object)

/**/*  w w w. java  2 s  .  c  om*/
 * Parse a text with a placeholder object
 * @param object
 * @returns {String}
 */
String.prototype.format = function format(object) {
    let parsed = this;
    for (const option in object) {
        if ({}.hasOwnProperty.call(object, option)) {
            const regex = new RegExp(`#{${option}}`, 'g');
            parsed = parsed.replace(regex, object[option]);
        }
    }

    return parsed;
};

export default String.prototype.format;



PreviousNext

Related