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?

Wain
  • 118,658
  • 15
  • 128
  • 151
soleil
  • 12,133
  • 33
  • 112
  • 183

5 Answers5

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 :)

Augustine P A
  • 5,008
  • 3
  • 35
  • 39
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.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • 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 '15 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 '15 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)];
casillas
  • 16,351
  • 19
  • 115
  • 215
  • 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 '15 at 19:44
0

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

jalone
  • 1,953
  • 4
  • 27
  • 46
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];
    }
Community
  • 1
  • 1
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53