@estarlincito/utils
Version:
A collection of utility functions designed to simplify and speed up development tasks in JavaScript and TypeScript projects.
62 lines (41 loc) • 1.69 kB
Markdown
The `toURL` function safely converts a string into a `URL` object, validating the format and handling errors gracefully.
- Converts a valid URL string into a `URL` object.
- Returns `undefined` and throws an error if the URL is invalid.
- Helps ensure proper URL validation before use in requests or navigation.
This function is part of `@estarlincito/utils`. Install it using:
```sh
pnpm add @estarlincito/utils
npm install @estarlincito/utils
yarn add @estarlincito/utils
```
Import the function in your project:
```ts
import { toURL } from '@estarlincito/utils';
const url = toURL('https://example.com');
console.log(url); // URL { href: 'https://example.com/', ... }
```
```ts
const validURL = toURL('https://google.com');
console.log(validURL?.href); // "https://google.com/"
const anotherValidURL = toURL('http://localhost:3000');
console.log(anotherValidURL?.href); // "http://localhost:3000/"
```
```ts
const invalidURL = toURL('invalid-url');
// Throws: "Invalid URL: invalid-url, example: 'https://example.com/'"
```
- **Try-Catch Handling:** It attempts to create a `URL` object using `new URL(url)`.
- **Error Handling:** If the input is not a valid URL, it triggers `handleError` with a descriptive message.
- **Ensures Validity:** Prevents invalid URLs from being used in API calls, navigation, or link generation.
This project is licensed under the MIT License - see the [LICENSE](../LICENSE) file for details.
**Author:** Estarlin R ([estarlincito.com](https://estarlincito.com))