Swift - Replacing emojis in a string with whitespace

前端 未结 6 1413
悲&欢浪女
悲&欢浪女 2020-12-18 11:05

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 s

6条回答
  •  爱一瞬间的悲伤
    2020-12-18 11:25

    Getting all emoji is more complicated than you would think. For more info on how to figure out which characters are emoji, check out this stackoverflow post or this article.

    Building on that information, I would propose to use the extension on Character to more easily let us understand which characters are emoji. Then add a String extension to easily replace found emoji with another character.

    extension Character {
       var isSimpleEmoji: Bool {
          guard let firstProperties = unicodeScalars.first?.properties else {
            return false
          }
          return unicodeScalars.count == 1 &&
              (firstProperties.isEmojiPresentation ||
                 firstProperties.generalCategory == .otherSymbol)
       }
       var isCombinedIntoEmoji: Bool {
          return unicodeScalars.count > 1 &&
                 unicodeScalars.contains {
                    $0.properties.isJoinControl ||
                    $0.properties.isVariationSelector
                 }
       }
       var isEmoji: Bool {
          return isSimpleEmoji || isCombinedIntoEmoji
       }
    }
    
    extension String {
        func replaceEmoji(with character: Character) -> String {
            return String(map { $0.isEmoji ? character : $0 })
        }
    }
    

    Using it would simply become:

    "Some string 

提交回复
热议问题