swiftstringarabicdiacriticsarabic-support

swift remove diacritic from Arabic


I am trying to remove the Arabic text diacritic. For example I need to convert this َب to this ب , here is my code :

if (text != "") {
    for char in text! {
        print(char)
        print(char.unicodeScalars.first?.value)
        if allowed.contains("\(char)"){
            newText.append(char)
        }
    }
    self.textView.text = text!
} else {
//            TODO :
//            show an alert
    print("uhhh no way")
}

I have tried these solutions but with no luck :

How to remove diacritics from a String in Swift?

NSString : easy way to remove UTF-8 accents from a string?


Solution

  • You can use Regex, try this code

     let myString = "الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ"
            let regex = try! NSRegularExpression(pattern: "[\\u064b-\\u064f\\u0650-\\u0652]", options: NSRegularExpression.Options.caseInsensitive)
            let range = NSMakeRange(0, myString.unicodeScalars.count)
            let modString = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "")
            print(modString)
    

    Output : الحمد لله رب العالمين