Freemarker 字符串处理

字符串处理(内置方法)

html安全输出

"abc<table>sdfsf"?html
返回安全的html输出,替换掉html代码

xml安全输出
var?xml

substring的用法

<#assign user="hello jeen">
${user[0]}${user[4]}
${user[1..4]}

输出 :

ho
ello

类似String.split的用法

"abc;def;ghi"?split(";")
返回 sequence
将字符串按空格转化成 sequence ,然后取 sequence 的长度
var?word_list 效果同 var?split(" ")
var?word_list?size

取得字符串长度
var?length

大写输出字符
var?upper_case

小写输出字符
var?lower_case

首字符大写
var?cap_first

首字符小写
var?uncap_first

去掉字符串前后空格
var?trim

每个单词的首字符大写
var?capitalize

类似String.indexof:
"babcdabcd"?index_of("abc") 返回1
"babcdabcd"?index_of("abc",2) 返回5
类似 String.lastIndexOf
last_index_ofString.lastIndexOf类似,同上

下面两个可能在代码生成的时候使用(在引号前加"\")
j_string: 在字符串引号前加"\"

<#assign beanName = 'The "foo" bean.'>
String BEAN_NAME = "${beanName?j_string}";

打印输出:

String BEAN_NAME = "The \"foo\" bean.";

js_string:

<#assign user = "Big Joe's \"right hand\".">
<script>
alert("Welcome ${user}!");
</script>

打印输出
alert("Welcome Big Joe\'s \"right hand\"!");

替换字符串 replace
${s?replace(‘ba’, ‘XY’ )}
${s?replace(‘ba’, ‘XY’ , ‘规则参数’)}
将s里的所有的ba替换成xy 规则参数包含: i r m s c f 具体含义如下:

  • i: 大小写不区分.
  • f: 只替换第一个出现被替换字符串的字符串
  • r: XY是正则表达式
  • m: Multi-line mode for regular expressions. In multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. By default these expressions only match at the beginning and the end of the entire string.
  • s: Enables dotall mode for regular expressions (same as Perl singe-line mode). In dotall mode, the expression + matches any character, including a line terminator. By default this expression does not match line terminators
  • c: Permits whitespace and comments in regular expressions.

字符串转换为数字
var?number