I have a URL in an iPhone application to work with. But the problem is that it has some spaces in the URL. I want to replace the spaces with '%20'. I know that there are the stringByReplacingOccurencesOfString
and stringByAddingPercentEscapesUsingEncoding
methods. I also have used them. But they are not working for me. The spaces are replaced by some unusual values.
I'm applying those methods on an instance of NSString
.
URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.
Just decode the url, use the replace function to eliminate the whitespaces and then encode it again.
In the above code, we have passed two arguments to the replace() method first one is regex /\s/g and the second one is replacement value + , so that the replace() method will replace all-white spaces with a + sign. The regex /\s/g helps us to remove the all-white space in the string.
The correct format for replacing space from url is :
Swift 4.2 , Swift 5
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Swift 4
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
Objective C
NSString *urlString;//your url string. urlString = [originalUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
or
urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iOS 9 and later
urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With