1

How can all special characters be removed from a string without also removing emojis?

I've tried:

func removeSpecialCharsFromString(text: String) -> String {
    let okayChars : Set<Character> = 
        Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890-& ".characters)
    return String(text.characters.filter {okayChars.contains($0) })
}

– but this function also removes the emoji from the string.

Expected Result:

"Hello guys !? Need some money $ "

Actual Result:

"Hello guys Need some money "

kirusamma
  • 119
  • 11
  • This could be helpful - https://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji – mag_zbc Jul 11 '19 at 08:25
  • @mag_zbc Thanks, but I don't see how that link can help me.I already use the extension to see if my string contains emoji or not. – kirusamma Jul 11 '19 at 08:46
  • What do you mean by a "special character"? Do you mean "any non ASCII except emojis" or "English punctuation" or something else? Would the letter ü be considered a special character? – JeremyP Jul 11 '19 at 09:13
  • i mean all non ASCII character except emojis – kirusamma Jul 11 '19 at 09:40

2 Answers2

3

You can use below extension to make your sentence perfect as per desired output.

extension String {
    var condensedWhitespace: String {
        let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
        return components.filter { !$0.isEmpty }.joined(separator: " ")
    }

    func removeSpecialCharacters() -> String {
        let okayChars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890 ")
        return String(self.unicodeScalars.filter { okayChars.contains($0) || $0.properties.isEmoji })
    }
}

Example.

let input = "Hello guys !? Need some money $ "

print(input.removeSpecialCharacters().condensedWhitespace)
// Hello guys Need some money 
Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
2

The question here is how to understand if a character is an emoji or not. Swift has a handy isEmoji method that we can use.

Here is the updated function with the usage of isEmoji method:

func removeSpecialCharacters(from text: String) -> String {
    let okayChars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890-& ")
    return String(text.unicodeScalars.filter { okayChars.contains($0) || $0.properties.isEmoji })
}

And just in case someone is going to test the code above in Playground:

let input = "Hello guys !? Need some money $ "
let output = removeSpecialCharacters(from: input)
print(output)                    // Prints: Hello guys  Need some money  

Denis
  • 3,167
  • 1
  • 22
  • 23