How to use replace( ) method In Javascript
In this approach, we are using the replace method with regular expressions to escape HTML characters by replacing special characters like <, >, &, “, and ‘ with their corresponding HTML entities. Then, we use another set of replacement methods to unescape these HTML entities back to their original characters.
Syntax:
string.replace(searchValue, replaceValue)
Example: The below example uses the replace() method to escape & unescape HTML characters in a string in JavaScript.
let originalStr = '<p>Hello, GFG!</p>';
let escapeStr = originalStr.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
console.log('Escaped String:', escapeStr);
let unescapeStr = escapeStr.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
console.log('Unescaped String:', unescapeStr);
Output
Escaped String: <p>Hello, GFG!</p> Unescaped String: <p>Hello, GFG!</p>
How to escape & unescape HTML characters in string in JavaScript?
Escaping and unescaping HTML characters is important in JavaScript because it ensures proper rendering of content, preventing HTML injection attacks and preserving text formatting when displaying user-generated or dynamic content on web pages.