21

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.

2
  • 2
    Do you know Mervin? Or you are looking for @SomeName? Else, let range = attributedString.string.rangeOfString("Marvin") (in pseudo code, I'm not sure of the Swift methods names, but completion should help you). Commented Jun 29, 2017 at 8:27
  • @Larme Thank you, it's working. I was trying same with utf-8 string so it was showing the wrong result. Commented Jun 29, 2017 at 13:05

2 Answers 2

24

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")
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting wrong rang and as well how to find the ranges when you have multiple Mervin in attributed string
0

I wanted something similar but for AttributedString instead. It took me a while to find the solution, so I think I may document it here since this is the first search hit for my question.

let attributedString = AttributedString("🤣🤣🤣 @Mervin tester 🤣🤣🤣")
let substring = "Mervin"

// Iterating through all the occurrences of `substring`.
for range in attributedString.characters.ranges(of: substring) {
   // Do something with the current range
   attributedString[range].foregroundColor = .red
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.