I would like to hide sensitive user data in strings by replacing a certain subrange with asterisks. For instance, replace all characters except the first and last three, turning
"sensitive info"
into
"sen********nfo".
I have tried this:
func hideInfo(sensitiveInfo: String) -> String {
let fIndex = sensitiveInfo.index(sensitiveInfo.endIndex, offsetBy: -4)
let sIndex = sensitiveInfo.index(sensitiveInfo.startIndex, offsetBy: 3)
var hiddenInfo = sensitiveInfo
let hiddenSubstring = String(repeating: "*", count: hiddenInfo.count - 6)
hiddenInfo.replaceSubrange(sIndex...fIndex, with: hiddenSubstring)
return hiddenInfo
}
and it works. But it seems overcomplicated. Is there a simpler and/or more elegant way of achieving this?