Supertecnoboff
Supertecnoboff

Reputation: 6606

Detect & remove 'www' in NSURL

I have a macOS application. I need to remove the scheme and www part from any NSURL. This is what I have come up with:

// For testing purposes.
NSString *blogID = @"https://www.testing1234.tumblr.com";
    
// Create the corrected link string.
NSString *correctLink;
    
// Convert the string to a url.
NSURL *url = [NSURL URLWithString:blogID];
    
// Check if the url has a scheme.
    
if ([url scheme] != nil) {
    correctLink = [url host];
} else {
    correctLink = blogID;
}
    
// Ensure there are enough characters before
// performing the necessary 'www.' checks.
    
if ([correctLink length] > 4) {
        
    // Remove the first instance of 'www.'
    // from the blog url link string.
        
    if ([[correctLink substringToIndex:4] containsString:@"www."]) {
        correctLink = [correctLink substringFromIndex:4];
    }
}
    
NSLog(@"correctLink: %@", correctLink);

My question is: how can I reliably remove the www part of the string? For starters aren't there different variants of www such as www2? Does NSURL have any method that allows me to detect the www part of the string? (Just like how I can detect the http:// part of the string by calling scheme).

Update

I can't use stringByReplacingOccurrencesOfString because it will replace all occurrences of www. So if the URLhappens to be www.testsitewww.tumblr.com then it will become testsite.tumblr.com. That's not what I want, I only want to remove the first occurrence of www (or any other variants such as www2).

Upvotes: 0

Views: 287

Answers (3)

Nirav Kotecha
Nirav Kotecha

Reputation: 2581

Try this way. You can separate the url by "." and you can get remaining string.

- if www. or www2. or anything else comes it will separate by "." and you can get remaining string

NSString *blogID = @"https://www.testing1234.tumblr.com";
    NSString *correctLink;
    NSURL *url = [NSURL URLWithString:blogID];
    if ([url scheme] != nil) {
        correctLink = [url host];
    } else {
        correctLink = blogID;
    }
    NSArray *arr = [correctLink componentsSeparatedByString:@"."];
    NSString *str = @"";
    for(int i=1; i<arr.count; i++)
    {
        str = [str stringByAppendingString:[arr objectAtIndex:i]];
        if(i != arr.count-1)
            str = [str stringByAppendingString:@"."];
    }
    NSLog(@"correctLink: %@", str); //correctLink: testing1234.tumblr.com

Upvotes: 1

Vikas Rajput
Vikas Rajput

Reputation: 1874

do this

NSString *blogID = @"https://www.testing1234.tumblr.com";
[blogID stringByReplacingOccurrencesOfString:@"www" withString:@""];
//or
[blogID stringByReplacingOccurrencesOfString:@"www." withString:@""];

or

 if([blogID hasPrefix:@"www"]) {
//do stuff
 }

Upvotes: 0

Piotr Golinski
Piotr Golinski

Reputation: 1000

You can replace part of text ex:

NSString* url = [urlWithWWW stringByReplacingOccurrencesOfString:@"www." withString:@""];

Upvotes: 0

Related Questions