Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace occurrences of space in URL

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.

like image 232
Joy Avatar asked Aug 09 '10 12:08

Joy


People also ask

How do I change the spaces in a URL?

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.

How do I remove spaces from a URL?

Just decode the url, use the replace function to eliminate the whitespaces and then encode it again.

How do you replace a space in react?

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.


1 Answers

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]]; 
like image 193
Raj Avatar answered Sep 21 '22 23:09

Raj