Safely encode a URL, excluding already-encoded sequences, handling unmatched surrogate pairs.
| Argument |
Description |
Type |
string |
Encoded URL |
string |
| Parameter |
Description |
Type |
Default |
url |
URL to encode |
string |
Required |
import { encodeUrl } from 'ranuts';
const url = 'https://example.com/path with spaces';
const encoded = encodeUrl(url);
console.log(encoded); // 'https://example.com/path%20with%20spaces'
import { encodeUrl } from 'ranuts';
// Already encoded parts won't be re-encoded
const url = 'https://example.com/path%20with%20spaces';
const encoded = encodeUrl(url);
console.log(encoded); // 'https://example.com/path%20with%20spaces'
import { encodeUrl } from 'ranuts';
const url = 'https://example.com/search?q=hello world&lang=zh-CN';
const encoded = encodeUrl(url);
console.log(encoded); // Encoded URL
import { encodeUrl } from 'ranuts';
// Invalid encoding sequences (like %foo) will be re-encoded
const url = 'https://example.com/path%foo';
const encoded = encodeUrl(url);
console.log(encoded); // 'https://example.com/path%25foo'
- Smart encoding: Only encodes unencoded parts, already-encoded sequences (like
%20) remain unchanged.
- Surrogate pair handling: Automatically handles unmatched surrogate pairs, replaces with Unicode replacement character.
- Safety: Won't throw errors, will try to encode URL correctly as much as possible.
- Use case: Commonly used to handle user-input URLs, build safe URLs, etc.