Search code examples
htmlgrailsmethodsgroovytags

How to call my created method on my getProjectLists in order to remove HTML tags from String


This is my getProjectLists action

  def getProjectLists() {
      def currentUser = springSecurityService.currentUser
      def kups = ([['name':'<b>Sample 1</b>'.removeHthml()],
      ['name':'<b>Sample 2</b>']])
  render kups as JSON  
 }

And this is my class and method

class HtmlTagRemove {
    static String removeHthml(String inputStr) {
      return inputStr.replaceAll("<.*?>","")
    }
}

This the error I encountered

No signature of method: java.lang.String.removeHtml() is applicable for argument types: () value: []

FOLLOW-UP (Even though the original question was answered, my follow up question is as follows)

What can I do to make my method callable from a String like: '<b>Sample 1</b>'.removeHtml()?


Solution

  • Answering the follow-up question:

    You could extend the String class. Documentation

    ​String.metaClass.removeHtml {    
        delegate.replaceAll("<.*?>","")
    }
    
    '<b>Sample 1</b>'.removeHtml()
    

    I would use a library like Jsoup to remove html from a string:

    Document doc = Jsoup.parse(html)
    return doc.text())