简体   繁体   中英

Remove http:// from NSString

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

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)

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];
NSString *newString = [myString stringByReplacingOccurrencesOfString:@"http://"
                                                          withString:@""
                                                             options:NSAnchoredSearch // beginning of string
                                                               range:NSMakeRange(0, [myString length])]

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

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:@""];

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.

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)

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
   }
}

由于该线程仍然处于活动状态并出现在我的搜索中以从 URL(不是 NSString)中删除前缀......如果您以 URL 开头,则有一个单行:

String(url.absoluteString.dropFirst((url.scheme?.count ?? -3) + 3))

Here is another option;

NSMutableString *copiedUrl = [[urlAddress mutablecopy] autorelease];
[copiedUrl deleteCharactersInRange: [copiedUrl rangeOfString:@"http://"]];

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

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"

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;
}

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

NSRange dividerRange = [str rangeOfString:@"://"];
NSString *newString = [str substringFromIndex:NSMaxRange(dividerRange)];

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]; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM