0
votes

I am using scala with play framework.I want to make a hash-tag system like twitter. But I am having problems in case of multi hash-tag. Here is my controller code..

 def hashTag = Action{ implicit request =>
      val body = request.body.asFormUrlEncoded
      var textValue=body.get("text").get(0) //get text value from post method
      textValue = textValue.trim()
      val array = textValue.split(" ")      //split from 'space' to get first word
      val firstWord = array(0)
      if (firstWord.length() > 1) {
         val split = firstWord.split("#")   //split word from #
         if (split.length >= 2) {
            val hashTag = split(1)          //fetch first hash-tag from textValue variable
            val link = "<a href=\"/hashtag/" + hashTag + "\">" + hashTag + "</a>" //create a link to hash-tag page
            textValue=textValue.replace(hashTag, link)

             //Insert textValue in database
            }//end if
        }//end if
}//end hashTag

If i give the input like the string given below then i got hyper link on both instances of Scala hash-tag but not on Java hash-tag. I want to replace Java hash-tag with < a href='/hashtag/Java'>Java and store in database.

#scala #java #scala

How can i do it,please help. Thanks in advance.

1

1 Answers

1
votes

Your code isn't running because you don't actually have a loop through all the hashtags. It just takes the first hashtag it finds and replaces that in the string, and doesn't continue on to the next.

Your solution can be simplified a lot if you use Regular Expressions. You could define a regex that matches hashtags: #(\w+). In the regex \w+ means that we're matching word characters, and #(\w+) means we're matching word characters after a # symbol. If you would like to also support digits then just extend it with \d in the following way: #([\w\d]+)

In Scala regular expressions would be used in the following way:

val textValue: String = "#scala #java #scala"  // Our strings we're testing
val hashTagPattern: Regex = """#(\w+)""".r     // The regular expression we defined
val textWithLinks: String = hashTagPattern.replaceAllIn(textValue, { m =>
  val hashTag = m.group(1)  // Group 1 is referencing the characters in the parentheses
  s"""<a href="/hashtag/$hashTag">$hashTag</a>"""       // We assemble the link using string interpolation
})
println(textWithLinks)
// Output: <a href="/hashtag/scala">scala</a> <a href="/hashtag/java">java</a> <a href="/hashtag/scala">scala</a>

So we define a hashTagPattern and then call replaceAllIn, which takes two parameters: the string to replace in and a function that processes a Match. The type definition of this function is: Match => String.

Next we create this function: m is our match and we use .group(1) to get the hashtag string after the # symbol. After we have that we can use string literals """...""" to not have to escape the strings and string interpolation to assemble our link with $variableName embeded in our strings.