OneBite.Dev - Coding blog in a bite size

remove a substring from a string in Go

Code snippet on how to remove a substring from a string in Go

  package main 
  
  import "strings"
  
  func main() {
    // original string
    str := "Hello, world!"
    
    // substring to remove
    substring := ", world!"
    
    // find the substring index
    substringIndex := strings.Index(str, substring)
    
    // perform the trimming
    trimmedStr := str[:substringIndex]
    
    println(trimmedStr) // "Hello"
  }

This code shows how to remove a substring from an existing string. First, the original string is declared and the substring to be removed is defined. Then, the strings.Index function is used to find the index of where the subtring starts in the string. Finally, the original string is trimmed and the substring is removed. The result is the original string with the substring removed.

go