title: Golang truncate strings with special characters without corrupting data
body: <p>I am trying to write a function to truncate strings with special characters in golang. One example is below</p>
  
  <p><code>"H㐀〾▓朗퐭텟şüöžåйкл¤"</code></p>
  
  <p>However I am doing it based on the number of characters allowed and cutting it in the middle. This results in data getting corrupted. </p>
  
  <p>The result comes out like</p>
  
  <p><code>H㐀〾▓朗퐭텟şüöžå�...</code></p>
  
  <p>The <code>�</code> should not be there. How do we detect these special characters and split it based on the length of these characters?</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "regexp"
  )
  
  var reNameBlacklist = regexp.MustCompile(`(&amp;|&gt;|&lt;|\/|:|\n|\r)*`)
  var maxFileNameLength = 30
  
  // SanitizeName sanitizes user names in an email
  func SanitizeName(name string, limit int) string {
  
      result := name
      reNameBlacklist.ReplaceAllString(result, "")
      if len(result) &gt; limit {
          result = result[:limit] + "..."
      }
      return result
  }
  
  
  
  func main() {
    str := "H㐀〾▓朗퐭텟şüöžåйкл¤"
      fmt.Println(str)
  
      strsan := SanitizeName(str, maxFileNameLength)
      fmt.Println(strsan)
  
  }
  </code></pre>