diff --git a/snippets/escapeString.md b/snippets/escapeString.md index a1bf2fc7f..7ca23af6d 100644 --- a/snippets/escapeString.md +++ b/snippets/escapeString.md @@ -1,14 +1,19 @@ -### escapeString +### escapeHTML Escapes a string for use in HTML. -Use a chain of `String.replace()` calls combined with regular expressions to replace special characters with the proper symbols. +Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object). ```js -const escapeString = str => - str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>'); +const escapeHTML = str => str.replace(/[&<>'"]/g, tag => ({ + '&': '&', + '<': '<', + '>': '>', + '\'': ''', + '"': '"' + })[tag] || tag); ``` ```js -escapeString('Me & you'); // '<a href="#">Me & you</a>' +escapeHTML('Me & you'); // '<a href="#">Me & you</a>' ```