JavaScript替换HTML标签
1、说明
获取HTML字符串(包含标签),通过正则表达式替换HTML标签,输出替换后的字符串
2、实现JavaScript代码
function deleteTag() { var regx = /<[^>]*>|<\/[^>]*>/gm; var tagStr = $("#ul_li").html(); alert("替换之前的字符串:" + tagStr); var result = tagStr.replace(regx,""); alert("替换之后的字符串:" + result); }
3、运行结果
(1)初始化时
(2)单击按钮后
(3)单击“确定”后
4、附录
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>JavaScript替换HTML标签</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="js/jquery-1.11.0.js"></script> <script type="text/javascript"> function deleteTag() { var regx = /<[^>]*>|<\/[^>]*>/gm; var tagStr = $("#ul_li").html(); alert("替换之前的字符串:" + tagStr); var result = tagStr.replace(regx,""); alert("替换之后的字符串:" + result); } </script> </head> <body> <ul id="ul_li"> <li class="peach">桃树</li> <li class="pear">梨树</li> <li>樟树</li> <li>枫树</li> <li>松树</li> </ul> <input type="button" value="替换HTML标签" onclick="deleteTag()"/> </body> </html>