String manipulation in URLs can involve various tasks such as parsing, encoding, decoding, constructing, and modifying URLs. Here are some common operations and examples in different programming languages:
Example: Parsing and constructing URLs using `urllib.parse`.
```
from urllib.parse import urlparse, urlunparse, urlencode, parse_qs
Example: Using the `URL` and `URLSearchParams` APIs.
```
// URL parsing
let url = new URL;
console.log(url.hostname); // Output: www.example.com
console.log(url.searchParams.get(‘name’)); // Output: John
// URL encoding
let params = new URLSearchParams();
params.append(‘name’, ‘John Doe’);
params.append(‘city’, ‘New York’);
console.log(params.toString()); // Output: name=John+Doe&city=New+York
// URL constructing
let newUrl = new URL;
newUrl.search = params;
console.log(newUrl.toString()); // Output: https://www.example.com/page?name=John+Doe&city=New+York
```
Example: Using `URI` and `URLEncoder`.
```
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
public class URLManipulationExample { public static void main(String[] args) throws URISyntaxException, UnsupportedEncodingException { // URL parsing URI uri = new URI; System.out.println(uri.getHost()); // Output: www.example.com System.out.println(uri.getQuery()); // Output: name=John&age=30
// URL encoding String name = URLEncoder.encode(“John Doe”, “UTF-8”); String city = URLEncoder.encode(“New York”, “UTF-8”); System.out.println(“name=” + name + “&city=” + city); // Output: name=John+Doe&city=New+York // URL constructing String newUri = “https://www.example.com/page?” + “name=” + name + “&city=” + city; System.out.println(newUri); // Output: https://www.example.com/page?name=John+Doe&city=New+York } } ```
Example: Parsing, encoding, and constructing URLs using PHP.
```
// URL parsing
$url = “https://www.example.com/page?name=John&age=30”;
$parsed_url = parse_url($url);
print_r($parsed_url[‘host’]); // Output: www.example.com
parse_str($parsed_url[‘query’], $query_params);
print_r($query_params[‘name’]); // Output: John
// URL encoding
$params = array(‘name’ => ‘John Doe’, ‘city’ => ‘New York’);
$encoded_params = http_build_query($params);
echo $encoded_params; // Output: name=John+Doe&city=New+York
// URL constructing
$new_url = “https://www.example.com/page?” . $encoded_params;
echo $new_url; // Output: https://www.example.com/page?name=John+Doe&city=New+York
?>
```
Using these examples, you can effectively perform string manipulations in URLs across different programming environments.