Remove part of an NSString
Asked Answered
E

3

5

I have an NSString as follows:

<img alt="996453912" src="http://d2gg0uigdtw9zz.cloudfront.net/large/996453912.jpg" /><a href="http://www.dealcatcher.com/shop4tech-coupons">Shop4Tech Coupons</a>

I only need the first part (before the <a href part), and I cannot figure out how to remove the second part.

I have tried a ton, but it has not worked.

Eighteen answered 12/12, 2010 at 18:31 Comment(2)
Which methods have you tried?Greenebaum
I have tried Componentsseperatedby and have looked for others, but cannot find others.Eighteen
D
18

Use something like:

NSRange rangeOfSubstring = [string rangeOfString:@"<a href"];

if(rangeOfSubstring.location == NSNotFound)
{
     // error condition — the text '<a href' wasn't in 'string'
}

// return only that portion of 'string' up to where '<a href' was found
return [string substringToIndex:rangeOfSubstring.location];

So the two relevant methods are substringToIndex: and rangeOfString:.

Dosage answered 12/12, 2010 at 18:55 Comment(0)
G
3

There is a section in the NSString Class reference about Finding Characters and Substrings which lists some helpful methods.

And in the String Programming Guide There is a section on Searching, Comparing and Sorting Strings.

I'm not being shirty in pointing out these links. You've said that you've couldn't find methods so here are a couple of references to help you know where to look. Learning how to read the documentation is part of learning how to use the Cocoa and Cocoa-Touch Frameworks.

Greenebaum answered 12/12, 2010 at 20:5 Comment(0)
M
0

You could use something similar to this modified version of what was posted as an answer to a similar question here https://mcmap.net/q/202427/-remove-html-tags-from-an-nsstring-on-the-iphone. This will take your HTML string and strip out the formatting. Just modify the while part to remove the regex of what you want to strip:

-(void)myMethod
{
   NSString* htmlStr = @"<some>html</string>";
   NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];
}

-(NSString *)stringByStrippingHTML:(NSString*)str
{
  NSRange r;
  while ((r = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
  {
     str = [str stringByReplacingCharactersInRange:r withString:@""];
  }
  return str;
}
Moria answered 31/5, 2013 at 12:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.