The lodash method _.escape exported as a standalone module for converting HTML entities in strings
npx @tessl/cli install tessl/npm-lodash--escape@3.2.0lodash.escape is the lodash method _.escape exported as a standalone module. It provides HTML entity escaping for strings to prevent XSS attacks by converting HTML special characters (&, <, >, ", ', `) to their corresponding HTML entities.
npm install lodash.escapeconst escape = require('lodash.escape');For ES modules:
import escape from 'lodash.escape';const escape = require('lodash.escape');
// Basic HTML escaping
const userInput = 'Hello <script>alert("XSS")</script> & welcome!';
const safeHtml = escape(userInput);
console.log(safeHtml);
// => 'Hello <script>alert("XSS")</script> & welcome!'
// Common use case: preparing data for HTML attributes
const userName = 'John "Johnny" O\'Malley';
const htmlAttribute = `<div data-user="${escape(userName)}">`;
// => '<div data-user="John "Johnny" O'Malley">'Converts HTML special characters in strings to their corresponding HTML entities to prevent XSS attacks and ensure safe rendering in HTML contexts.
/**
* Converts the characters "&", "<", ">", '"', "'", and "`" in string to their corresponding HTML entities.
* @param {string} [string=''] - The string to escape.
* @returns {string} Returns the escaped string.
*/
function escape(string)Character Mappings:
| Input Character | HTML Entity |
|---|---|
& | & |
< | < |
> | > |
" | " |
' | ' |
` | ` |
Important Notes:
/ character is not escaped, as it doesn't require escaping in HTMLUsage Examples:
const escape = require('lodash.escape');
// All escapable characters
escape('&<>"\'`');
// => '&<>"'`'
// Mixed content with unescapable characters
escape('Hello & goodbye/world');
// => 'Hello & goodbye/world'
// Empty and null handling
escape(''); // => ''
escape(null); // => ''
escape(undefined); // => ''
// Non-string input
escape(123); // => '123'
escape(true); // => 'true'
// Strings with no escapable characters
escape('Hello world'); // => 'Hello world'
// Template usage
const templateData = {
title: 'News & Updates',
content: 'Check out our "latest" features!'
};
const html = `
<h1>${escape(templateData.title)}</h1>
<p>${escape(templateData.content)}</p>
`;
// Safe HTML output with escaped entitiesCommon Use Cases: