Swift iOS Mask a string "Hello" to "Hxxxo"

There is a Regular Expression way with lookaround

extension String {
    var masked: String {
        replacingOccurrences(
            of: "(?!^).(?!$)", // RegEx
            with: "x", // Replacement
            options: .regularExpression // Option to set RegEx
        )
    }
}

You can enumerate the string and apply map transform to get the expected output:

extension String {
  var masked: String {
    self.enumerated().map({ (index, ch) in
      if index == 0
        || index == self.count - 1 {
        return String(ch)
      }
      return "x"
    }).joined()
  }
}

let str = "hello"
print("after masking \(str.masked)") // Output - hxxxo

The map transform will return an array, so use joined() to convert the array back to String. Also, note that you have to typecast ch to String as String(ch) because the type of ch is 'String.Element' (aka 'Character').

Tags:

String

Ios

Swift