การลบแท็ก HTML ออกจากสตริง
เราสามารถลบ HTML/XML แท็กในสตริงโดยใช้นิพจน์ทั่วไปใน javascript . องค์ประกอบ HTML เช่น span, div เป็นต้น อยู่ระหว่างลูกศรซ้ายและขวา เช่น
, เป็นต้น ดังนั้นการแทนที่เนื้อหาภายในลูกศร พร้อมกับลูกศร โดยที่ไม่มีอะไร ('') จะทำให้งานของเรา ง่าย
ไวยากรณ์
str.replace( /(<([^>]+)>)/ig, '');
ตัวอย่าง-1
<html>
<body>
<script>
function removeTags(str) {
if ((str===null) || (str===''))
return false;
else
str = str.toString();
return str.replace( /(<([^>]+)>)/ig, '');
}
document.write(removeTags('<html> <body> Javascript<body> is not Java'));;
</script>
</body>
</html> ผลลัพธ์
Javascript is not Java
ตัวอย่าง-2
<html>
<body>
<script>
function removeTags(str) {
if ((str===null) || (str===''))
return false;
else
str = str.toString();
return str.replace( /(<([^>]+)>)/ig, '');
}
document.write(removeTags('<html> Tutorix is <script> the best <body> e-learning platform'));;
</script>
</body>
</html> ผลลัพธ์
Tutorix is the best e-learning platform