← Back Home

Cut string between two delimiters in Go

  1. go
  2. golang
  3. programming
  4. strings

There are times when we need to cut/get a string between 2 delimiters. Regex is one of the solution to accomplish this, but we can also use string.Index in Go code to do same. Following is an example of how to accomplish this in Go.

    func cutBetweenTwoDelimiters(str, startDelimiter, endDelimiter string) string {
        // get index of first delimiter in string
        start := strings.Index(str, startDelimiter)
        if start == -1 {
            return ""

        start += len(startDelimiter)

        // get index of end delimiter in string
        end := strings.Index(str[start:], endDelimiter)
        if end == -1 {
            return ""

        // return the string between those two indexes
        return str[start : start+end]