学科分类
目录
Java Web

fn:substring、fn:substringAfter与fn:substringBefore

在程序开发中,经常需要截取一个字符串中指定的部分,为了在JSP页面中完成这种功能,Functions标签库提供了三个函数,具体如下:

1、fn:substring函数:

fn:substring函数用于截取一个字符串中指定子字符串并返回截取到的子字符串,其语法格式如下:

fn:substring(String source,int beginIndex,int endIndex) → String

上述语法格式中,可以看到fn:substring函数需要接收三个参数,其中,source参数用于指定源字符串,beginIndex参数用于指定截取字符串开始的索引值,endIndex参数用于指定截取子字符串结束的索引值,beginIndex参数和endIndex参数都是int类型,其值都是从0开始。需要注意的是,在截取字符串时包含beginIndex位置的字符,不包含endIndex位置的字符。

2、fn:substringBefore函数

fn:substringBefore函数用于截取并返回指定字符串之前的子字符串,其语法格式如下:

fn:substringBefore(String **source**,String target) → String

上述语法格式中,可以看到fn:substringBefore函数需要接收两个String类型参数,其中,source参数用于指定源字符串,target用于指定子字符串。如果源字符串不包含子字符串,则返回空字符串。

3、fn:substringAfter函数

fn:substringAfter用于截取并返回指定字符串之后的子字符串,其语法格式如下:

fn:substringAfter(String **source**,String target) → String

上述语法格式中,可以看到fn:substringAfter函数与fn:substringBefore函数类似,同样需要接收两个String类型参数,source参数用于指定源字符串,target用于指定子字符串。如果源字符串不包含子字符串,则返回空字符串。

​ 为了更好的学习和使用上面的三个函数,接下来,通过一个案例来演示它们的具体用法,如例1所示。

例1 fn_substring.jsp

 1  <%@ page language="java" contentType="text/html; charset=utf-8"

 2  pageEncoding="utf-8" import="java.util.*"%>

 3  <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

 4  <html>

 5  <head></head>

 6  <body>

 7    fn:substring("welcome to itcast!",3,9)返回的结果为:

 8    ${fn:substring("welcome to itcast!",3,9) } <br> 

 9    fn:substringBefore("mydata.txt",".")返回的结果为:

 10   ${fn:substringBefore("mydata.txt",".") } <br> 

 11   fn:substringAfter("mydata.txt",".")返回的结果为:

 12   ${fn:substringAfter("mydata.txt",".") } <br> 

 13 </body>

 14 </html>

打开IE浏览器,在地址栏中输入http://localhost:8080/chapter08/fn_substring.jsp访问fn_substring.jsp页面,此时,浏览器窗口中显示的结果如图1所示。

图1 fn_substring.jsp

从图1可以看出,使用fn:substring函数可以截取指定的字符串,使用fn:substringBefore函数可以截取“.”字符之前的字符串,使用fn:substringAfter函数可以截取“.”字符之后的字符串,这三个函数最终都会返回截取后的字符串。

点击此处
隐藏目录