在html或jsp等前端页面上要对出现html标签的地方敏感一点
因为一旦页面上出现不完整的html标签那么你的页面就会崩溃从而导致你手足无措
我曾遇到一个问题是之前系统页面没有问题,数据本身也没有问题
但导入新的数据之后,html页面就是无法正常显示,非常崩溃
然后想到jsp的页面有个别模块是从文本中提取一段可能带html标签的文本进行显示
而该文本又是随机截取定长字符
那么问题就来了,截取之后若出现不完整的html标签怎么办呢?
答案很简单:你的页面会惨不忍睹,那一刻你会很无奈,因为之前没问题呀!O(∩_∩)O哈哈~
下面提供一些去除html标签的方法:
java(jsp)端只提取中文内容:
String regex="([\u4e00-\u9fa5]+)"; String aimStr = ""; Matcher matcher = Pattern.compile(regex).matcher(aimStr); if(matcher.find()){ aimStr = matcher.group(0); } System.out.println(aimStr);
java(jsp)端去除html标签:
public String removeHtmlTag() { //使用该方法记得引入相应的类 String htmlStr = "";//带有html标签的文本内容 String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 去除script String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 去除style String regEx_html = "<[^>]+>"; // 去除HTML tag String regEx_space = "\\s+|\t|\r|\n";// 去除other characters Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); Pattern p_style = Pattern .compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); Pattern p_space = Pattern .compile(regEx_space, Pattern.CASE_INSENSITIVE); Matcher m_space = p_space.matcher(htmlStr); htmlStr = m_space.replaceAll(" "); return htmlStr; }
js端只提取中文内容:
aimStr.replace(/[^\u4e00-\u9fa5]/gi,"");
js端去除html标签:
aimStr.replace(/<[^>]+>/g,"");