Dùng Regular Expression để tìm và thay thế tất cả thẻ HTML (<tag>, </tag>, <tag attr="...">) bằng chuỗi rỗng.
Regex pattern
/<([^>]+)>/g
Giải thích:
<— ký tự mở thẻ.([^>]+)— nhóm capture: một hoặc nhiều ký tự không phải>(tên thẻ + attribute).>— ký tự đóng thẻ./g— global (thay thế tất cả).
Hàm tiện ích
<script>
function stripHtmlTags(str) {
if (str === null || str === '') return '';
return String(str).replace(/<[^>]+>/g, '');
}
// Test
document.write(stripHtmlTags('Javascript is not Java'));
// Output: "Javascript is not Java"
document.write('<br>');
document.write(stripHtmlTags(' Tutorix is