Here's my code in order to replace HTML tags:
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
}
And here is the code form my controller:
def getProjectLists() {
def currentUser = springSecurityService.currentUser
def kups = ([['name':'<b>Sample 1</b>'.removeHtml()],['name':'<b>Sample 2</b>']])
render kups as JSON
}
My expected output is:
< b >Sample1< / b> Sample2
But the output is:
Sample1 Sample2
I think what you really want is to escape HTML - display HTML tags and entities, so the function's name removeHtml
is a bit misleading, escapeHtml
would fit it better.
Generally I recommend not to do things like this by your self as others have already done that and most likely do it better.
For example Apache Commons has an StringEscapeUtils.escapeHtml
method.
String.metaClass.removeHtml {
return org.apache.commons.lang.StringEscapeUtils.escapeHtml(delegate)
}