Skip to content

[Cookbook] Trim String Indent

Camilo edited this page Apr 29, 2021 · 1 revision

Ruby shared how you can trim the indent from Strings. Although Raw strings have this capability by default. It would be useful for normal strings too.

static indent(string) {
  var index = 0
  var bytes = string.bytes
  while(index < bytes.count) {
    var c = bytes[index]
    if(c == 0x20 || c == 0x09) {
      index = index + 1
      continue
    }
    return index
  }
  return 0
}

static indent_strip(string) {
  var start = indent(string)
  if(start == 0) return string
  var lines = string.split("\n")
  lines = lines.map {|line|
    var left = indent(line)
    if(left >= start) return line[start..-1]
    return line
  }
  return lines.join("\n")
}