Search code examples
iosstringemailswift3replacewith

How to replace Email id text before @ with * in swift 3.0


Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")

Any suggestion is accepted.

Thank you.


Solution

  • Use init(repeating:count:)

      let newstr = "Himmoradiya@gmail.com"
      var token = newstr.components(separatedBy: "@")
      let newQuery = String(repeating: "*", count: token[0].characters.count)  //check array length before using index
      print(newQuery + "@" +  token[1] ) // *******@gmail.com