3

This works for a regular NSString:

NSString *newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];

But there is no such method for NSMutableAttributedString. How could I remove all instances of a comma in an NSMutableAttributedString?

0

5 Answers 5

7
let attrString = NSMutableAttributedString(string: "Hello <b>friend<b>")

attrString.mutableString.replaceOccurrencesOfString("<b>", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: NSRange(location: 0, length: attrString.length))

Try this :)

1

Do it before you create the attributed string, if you can or depending on how you source it. If you can't then you can use replaceCharactersInRange:withString: (or replaceCharactersInRange:withAttributedString:), but you need to know the range so you need to search and iterate yourself.

2
  • I already have the attributed string. It may include text attachments, etc. I know I have to use replaceCharactersInRange:withString but like you said, I don't know the ranges.
    – soleil
    Apr 14, 2015 at 19:45
  • That's why you would preferentially 'fix' the string first. You can get the string - the plain version of the attributed string - and find the range of the target string. But, you need to get it on each iteration as you'll be mutating the original string, or track the mutation range...
    – Wain
    Apr 14, 2015 at 19:48
1
NSString *newString= "I want to ,show, you how to achieve this";
NSMutableAttributedString *displayText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",newString]];
[[displayText mutableString] replaceOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, displayText.string.length)];
1
  • The first version didn't work, because you assigned an immutable string to newString. The second version: Why on earth are you using stringWithFormat?
    – gnasher729
    Apr 14, 2015 at 19:44
0

You can initialize the attributed string with the stripped string with the designed init. No?

0

The code could be applied from my answer here:

NSAttributedString *attributedString = ...;
NSAttributedString *anotherAttributedString = ...; //the string or characters which will replace

while ([attributedString.mutableString containsString:@"replace"]) {
        NSRange range = [attributedString.mutableString rangeOfString:@"replace"];
        [attributedString replaceCharactersInRange:range  withAttributedString:anotherAttributedString];
    }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.