在JavaScript中,可以使用内置的encodeURIComponent函数来转义HTML字符串,以确保它们在HTML中安全使用。以下是一个简单的转义函数示例:
function htmlEscape(str) {
return str.replace(/[&<>"']/g, function(match) {
const escape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return escape[match];
});
}
// 使用示例
const escapedHtml = htmlEscape('<p class="test">Hello, "World" & JavaScript</p>');
console.log(escapedHtml);