UNPKG

@gravityforms/utils

Version:
35 lines (32 loc) 892 B
/** * @module saferHtml * @description Escapes HTML special characters from a template literal. * * @since 1.0.0 * * @param {string} templateData The template literal to be escaped. * * @return {string} Returns the template string, with HTML special characters escaped. * * @example * import { saferHtml } from "@gravityforms/utils"; * * function Example() { * const str = 'my encoded <b>bold</b> text'; * const encodedString = saferHtml`<div>${ str }</div>`; * } * */ export default function( templateData ) { let s = templateData[ 0 ]; for ( let i = 1; i < arguments.length; i++ ) { const arg = String( arguments[ i ] ); // Escape special characters in the substitution. s += arg.replace( /&/g, '&amp;' ) .replace( /</g, '&lt;' ) .replace( />/g, '&gt;' ); // Don't escape special characters in the template. s += templateData[ i ]; } return s; }