7

How do I remove certain text from a NSString such as "http://"? It needs to be exactly in that order. Thanks for your help!

Here is the code I am using, however the http:// is not removed. Instead it appears http://http://www.example.com. What should I do? Thanks!

NSString *urlAddress = addressBar.text;
[urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""];
urlAddress = [NSString stringWithFormat:@"http://%@", addressBar.text];
NSLog(@"The user requested this host name: %@", urlAddress);
EmptyStack
  • 51,274
  • 23
  • 147
  • 178
Jack Humphries
  • 13,056
  • 14
  • 84
  • 125
  • 1
    You are again adding the same string. There is no need of 3rd line if you want to remove http:// – Nitish Aug 25 '11 at 04:55
  • If the user does not enter http://, then the UIWebView will work. However, if the user does enter http://, then the UIWebView will not work. By removing any http:// there is and then reinserting it once, I am guaranteed that the NSString will look like this: http:// www.google.com – Jack Humphries Aug 25 '11 at 04:57
  • possible duplicate of [Remove part of an NSString](http://stackoverflow.com/questions/4423248/remove-part-of-an-nsstring) – jscs Aug 25 '11 at 04:58

15 Answers15

19

Like this?

NSString* stringWithoutHttp = [someString stringByReplacingOccurrencesOfString:@"http://" withString:@""];

(if you want to remove text at the beginning only, do what jtbandes says - the code above will replace occurrences in the middle of the string as well)

SVD
  • 4,743
  • 2
  • 26
  • 38
  • @Jack Humphries - Krishnabhadra is right, you don't assign the changed value of urlAddress when you do stringByReplacingOccurrencesOfString: – SVD Aug 25 '11 at 04:59
9

Here's a solution which takes care of http & https:

    NSString *shortenedURL = url.absoluteURL;

    if ([shortenedURL hasPrefix:@"https://"]) shortenedURL = [shortenedURL substringFromIndex:8];
    if ([shortenedURL hasPrefix:@"http://"]) shortenedURL = [shortenedURL substringFromIndex:7];
Albert Schulz
  • 339
  • 3
  • 6
6
NSString *newString = [myString stringByReplacingOccurrencesOfString:@"http://"
                                                          withString:@""
                                                             options:NSAnchoredSearch // beginning of string
                                                               range:NSMakeRange(0, [myString length])]
jtbandes
  • 115,675
  • 35
  • 233
  • 266
3

Another way is :

NSString *str = @"http//abc.com";  
NSArray *arr = [str componentSeparatedByString:@"//"];  
NSString *str1 = [arr objectAtIndex:0];       //   http  
NSString *str2 = [arr objectAtIndex:1];       //   abc.com
Nitish
  • 13,845
  • 28
  • 135
  • 263
3

if http:// is at the start of the string you can use

 NSString *newString  = [yourOriginalString subStringFromIndex:7];

or else as SVD suggested

EDIT: AFter seeing question EDIT

change this line

[urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""];

to

urlAddress  = [urlAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""];
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
2

Since the thread is still active and showed up in my search to remove the prefix from a URL (not NSString)... there is a one-liner if you are starting with a URL:

String(url.absoluteString.dropFirst((url.scheme?.count ?? -3) + 3))
Beginner
  • 455
  • 7
  • 14
1

In case you wish to trim both sides and also write less code:

NSString *webAddress = @"http://www.google.co.nz";

// add prefixes you'd like to filter out here
NSArray *prefixes = [NSArray arrayWithObjects:@"https:", @"http:", @"//", @"/", nil];

for (NSString *prefix in prefixes)
    if([webAddress hasPrefix:prefix]) webAddress = [webAddress stringByReplacingOccurrencesOfString:prefix withString:@"" options:NSAnchoredSearch range:NSMakeRange(0, [webAddress length])];

// add suffixes you'd like to filter out here
NSArray *suffixes = [NSArray arrayWithObjects:@"/", nil];

for (NSString *suffix in suffixes)
    if([webAddress hasSuffix:suffix]) webAddress = [webAddress stringByReplacingOccurrencesOfString:suffix withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, [webAddress length])];

This code will remove specified prefixes from the front and suffixes from the back (like a trailing slash). Simply add more substrings to the prefix/suffix array to filter for more.

Thomas Verbeek
  • 2,361
  • 28
  • 30
1

Swift 3

For replacing all occurrences:

let newString = string.replacingOccurrences(of: "http://", with: "")

For replacing occurrences at the start of the string:

let newString = string.replacingOccurrences(of: "http://", with: "", options: .anchored)
César Cruz
  • 464
  • 4
  • 5
1

For those using swift and have arrived here.

extension String {

   func withoutHttpPrefix() -> String {
       var idx: String.Index?;
       if self.hasPrefix("http://www.") {
          idx = self.index(startIndex, offsetBy: 11)
       } else if hasPrefix("https://www.") {
           idx = self.index(startIndex, offsetBy: 12)
       } else if self.hasPrefix("http://") {
          idx = self.index(startIndex, offsetBy: 7)
       } else if hasPrefix("https://") {
           idx = self.index(startIndex, offsetBy: 8)
       }

       if idx != nil {
           return String(self[idx!...])
       }
       return self
   }
}
Umair
  • 1,203
  • 13
  • 15
1

Here is another option;

NSMutableString *copiedUrl = [[urlAddress mutablecopy] autorelease];
[copiedUrl deleteCharactersInRange: [copiedUrl rangeOfString:@"http://"]];
Sandeep
  • 20,908
  • 7
  • 66
  • 106
0

NSString* newString = [string stringByReplacingOccurrencesOfString:@"http://" withString:@""];

Saad Ur Rehman
  • 798
  • 1
  • 10
  • 19
0

Hi guys bit late but I come with a generic way Let's say:

NSString *host = @"ssh://www.somewhere.com";
NSString *scheme = [[[NSURL URLWithString:host] scheme] stringByAppendingString:@"://"]; 
// This extract ssh and add :// so we get @"ssh://" note that this code handle any scheme http, https, ssh, ftp ....
NSString *stripHost = [host stringByReplacingOccurrencesOfString:scheme withString:@""]; 
// Result : stripHost = @"www.somewhere.com"
Maple
  • 741
  • 13
  • 28
Benpaper
  • 144
  • 4
0

One more general way:

- (NSString*)removeURLSchemeFromStringURL:(NSString*)stringUrl {
    NSParameterAssert(stringUrl);
    static NSString* schemeDevider = @"://";

    NSScanner* scanner = [NSScanner scannerWithString:stringUrl];
    [scanner scanUpToString:schemeDevider intoString:nil];

    if (scanner.scanLocation <= stringUrl.length - schemeDevider.length) {
        NSInteger beginLocation = scanner.scanLocation + schemeDevider.length;
        stringUrl = [stringUrl substringWithRange:NSMakeRange(beginLocation, stringUrl.length - beginLocation)];
    }

    return stringUrl;
}
HotJard
  • 4,598
  • 2
  • 36
  • 36
0

This will remove any scheme including http, https, etc.

NSRange dividerRange = [str rangeOfString:@"://"];
NSString *newString = [str substringFromIndex:NSMaxRange(dividerRange)];
Rik
  • 1,870
  • 3
  • 22
  • 35
0

OR

+(NSString*)removeOpeningTag:(NSString*)inString tag:(NSString*)inTag {
    if ([inString length] == 0 || [inTag length] == 0) return inString;
    if ([inString length] < [inTag length]) {return inString;}
    NSRange tagRange= [inString rangeOfString:inTag];   
    if (tagRange.location == NSNotFound || tagRange.location != 0) return inString; 
    return [inString substringFromIndex:tagRange.length]; 
}
JAL
  • 3,319
  • 2
  • 20
  • 17