Find Range of substring in NSMutableAttributedString
Asked Answered
L

2

20

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.

Lysias answered 29/6, 2017 at 8:24 Comment(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).Jessejessee
@Jessejessee Thank you, it's working. I was trying same with utf-8 string so it was showing the wrong result.Lysias
D
23

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")
Dendritic answered 29/6, 2017 at 9:16 Comment(1)
I am getting wrong rang and as well how to find the ranges when you have multiple Mervin in attributed stringMalaise
N
-1

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
}
Ngo answered 13/8, 2023 at 15:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.