Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Replacing emojis in a string with whitespace

I have a method that detects urls in a string and returns me both the urls and the ranges where they can be found. Everything works perfectly until there are emojis on the string. For example:

"I'm gonna do this callenge as soon as I can swing again πŸ˜‚πŸ˜‚πŸ˜‚\n http://youtu.be/SW_d3fGz1hk"

Because of the emojis, the url extracted from the text is http://youtu.be/SW_d3fGz1 instead of http://youtu.be/SW_d3fGz1hk. I figured that the easiest solution was to just replace the emojis on the string with whitespace characters (cause I need the range to be correct for some text styling stuff). Problem is, this is extremely hard to accomplish with Swift (most likely my abilities with the Swift String API is lacking).

I've been trying to do it like this but it seems that I cannot create a string from an array of unicode points:

var emojilessStringWithSubstitution: String {
    let emojiRanges = [0x1F601...0x1F64F, 0x2702...0x27B0]
    let emojiSet = Set(emojiRanges.flatten())
    let codePoints: [UnicodeScalar] = self.unicodeScalars.map {
        if emojiSet.contains(Int($0.value)) {
            return UnicodeScalar(32)
        }
        return $0
    }
    return String(codePoints)
}

Am I approaching this problem the wrong way? Is replacing emojis the best solution here? If so, how can I do it?

like image 324
Raphael Avatar asked Apr 28 '16 15:04

Raphael


1 Answers

Swift 5

Don't use this hardcoded way to detect emojis. In Swift 5 you can do it easily

let inputText = "Some πŸ–string πŸ˜‚πŸ˜‚πŸ˜‚ with πŸ‘ΉπŸ‘Ή πŸ‘Ή emoji πŸ–"

let textWithoutEmoij = inputText.unicodeScalars
    .filter { !$0.properties.isEmojiPresentation }
    .reduce("") { $0 + String($1) }

print(textWithoutEmoij) // Some string  with   emoji 
like image 72
Abdelahad Darwish Avatar answered Sep 16 '22 12:09

Abdelahad Darwish