Search code examples
swiftnsattributedstringnsrangensmutableattributedstring

Find Range of substring in NSMutableAttributedString


I have AttributedString with emoji like this "🤣🤣🤣 @Mervin tester 🤣🤣🤣"

Now I need to find a range of Mervin in this attributed String.

let attributedString = NSMutableAttributedString(string: "🤣🤣🤣 @Mervin tester 🤣🤣🤣")

let range = // range for "Mervin" in above String. 

Thank you.


Solution

  • This extension should help you.

    extension NSAttributedString {
        func rangeOf(string: String) -> Range<String.Index>? {
            return self.string.range(of: string)
        }
    }
    

    Usage:

    attributedString.rangeOf(string: "Mervin")