delegate.replace() 不适用于 Array List Grails 2.3.8
delegate.replace() is not working on Array List Grails 2.3.8
这是我用来替换 HTML 标签的代码:
def str
String.metaClass.removeHtml {
def removeThisHtml = [
[htmlCode: "`", value: "`"],
[htmlCode: "@", value: "@"],
[htmlCode: "&", value: "&"],
[htmlCode: "\", value: "\"],
[htmlCode: """, value: '"'],
[htmlCode: "'", value: "'"],
[htmlCode: "<", value: "<"],
[htmlCode: ">", value: ">"]
]
removeThisHtml.each { element ->
str = delegate.replace(element.htmlCode, element.value)
}
return str
}
这是我的控制器的代码:
def getProjectLists() {
def currentUser = springSecurityService.currentUser
def kups = ([['name':'<b>Sample 1</b>'.removeHtml()],['name':'<b>Sample 2</b>']])
render kups as JSON
}
我的预期输出是:
样本 1样本 2
但输出是:
示例 1 示例 2
我认为你真正想要的是转义 HTML - 显示 HTML 标签和实体,所以函数名 removeHtml
有点误导, escapeHtml
会更合身。
一般来说,我建议您不要自己做这样的事情,因为其他人已经这样做了,而且很可能做得更好。
例如 Apache Commons 有一个 StringEscapeUtils.escapeHtml
方法。
String.metaClass.removeHtml {
return org.apache.commons.lang.StringEscapeUtils.escapeHtml(delegate)
}
这是我用来替换 HTML 标签的代码:
def str
String.metaClass.removeHtml {
def removeThisHtml = [
[htmlCode: "`", value: "`"],
[htmlCode: "@", value: "@"],
[htmlCode: "&", value: "&"],
[htmlCode: "\", value: "\"],
[htmlCode: """, value: '"'],
[htmlCode: "'", value: "'"],
[htmlCode: "<", value: "<"],
[htmlCode: ">", value: ">"]
]
removeThisHtml.each { element ->
str = delegate.replace(element.htmlCode, element.value)
}
return str
}
这是我的控制器的代码:
def getProjectLists() {
def currentUser = springSecurityService.currentUser
def kups = ([['name':'<b>Sample 1</b>'.removeHtml()],['name':'<b>Sample 2</b>']])
render kups as JSON
}
我的预期输出是:
样本 1样本 2
但输出是:
示例 1 示例 2
我认为你真正想要的是转义 HTML - 显示 HTML 标签和实体,所以函数名 removeHtml
有点误导, escapeHtml
会更合身。
一般来说,我建议您不要自己做这样的事情,因为其他人已经这样做了,而且很可能做得更好。
例如 Apache Commons 有一个 StringEscapeUtils.escapeHtml
方法。
String.metaClass.removeHtml {
return org.apache.commons.lang.StringEscapeUtils.escapeHtml(delegate)
}