HTMLタグ、行頭と行末の空白、改行を除いた文字数を取得するタグファイル

Javaのタグファイルで、HTMLタグ、行頭と行末の空白、改行を除いた文字数を取得するタグを作ってみました。
※最後の行をout.print(tmp_text);にすれば、テキスト部分のみを返すようにもできます。

タグファイル:(/WEB-INF/tags/validation/CountCharNumExcludingHtmlTags.tag)

<%@tag trimDirectiveWhitespaces="true"%>
<%@tag description="HTMLタグを除外した文字数をカウントする" pageEncoding="UTF-8"%><%@attribute name="text" description="文字数をカウントするテキスト" required="true"%>
<%!
    String tmp_text;
%>
<%
    tmp_text = text.toString();
    tmp_text = tmp_text.trim(); //行頭と行末の空白を削除
    tmp_text = tmp_text.replaceAll("<[^>]*>", ""); //HTMLタグを削除
    tmp_text = tmp_text.replaceAll("(\r\n|\n\r|\n|\r)", ""); //改行を削除
    out.print(tmp_text.length());
%>

以下のようにタグを使用します。
※${text}でHTML文を渡しています。

使用例:

<%@ taglib prefix="valid" tagdir="/WEB-INF/tags/validation" %>
<valid:CountCharNumExcludingHtmlTags text="${text}" />

公開日:2017年06月24日

記事 > Javaプログラミング > HTMLタグ、行頭と行末の空白、改行を除いた文字数を取得するタグファイル

他の記事も見る

このページのトップに戻る