als-normalize-urlpath
v2.3.0
Published
Normalize and sanitize relative URL paths
Downloads
18
Maintainers
Readme
als-normalize-urlpath
als-normalize-urlpath
is a library designed for normalizing and sanitizing URL paths in both Node.js and browser environments. It's especially useful for standardizing relative URL paths, removing unsafe characters, and ensuring URL consistency across different platforms.
Installation
Node.js
Node.js version 10 or higher is required, as the library utilizes the URL
class, which is not available in older versions of Node.js.
To install als-normalize-urlpath
, use npm:
npm install als-normalize-urlpath
Browser
For browser usage, include the library script in your HTML. Ensure you have a browser-compatible version of the library.
<script src="path_to_als-normalize-urlpath.js"></script>
Usage
Node.js
After installation, you can require and use the als-normalize-urlpath
in your Node.js application:
const normalizeUrlPath = require('als-normalize-urlpath');
const result = normalizeUrlPath('/some/path');
console.log(result);
Browser
In the browser, the normalizeUrlPath
function will be available after including the script:
const result = normalizeUrlPath('/some/path');
console.log(result);
Functionality
The normalizeUrlPath
function processes and normalizes relative URL paths. It performs the following operations:
- Input Validation: Checks if the input is a string.
- URL Validation: Ensures that the URL is not a full URL (e.g., starting with 'http:', 'mailto:', etc.) or a special URL (e.g., 'data:', 'blob:').
- Length Restriction: Limits the URL length to a maximum of 2000 characters.
- Security: Removes dot segments to prevent directory traversal attacks, illustrated by transforming /../test to /test.
- Normalization: Replaces backslashes with forward slashes and removes redundant slashes, turning \test\path into /test/path.
- Path Formatting: Adds a leading slash if absent and removes a trailing slash if present (except for the root /).
- Query Parsing: Parses query parameters into an object and retains the hash fragment.
Api
Syntax:
const params = {lower: false, translate: false, slug: false, trim: false};
const urlPath = 'String';
const throwError = false;
const result = normalizeUrlPath(urlPath, params, throwError);
Parameters
urlPath
(String): The URL path to be normalized. This should be a relative URL.params
(Object): Parameters for normalizing- default:
{lower:false,translate:false,slug:false,trim:false}
lower
: Converts the pathname to lowercase, enhancing URL consistency.special
: Converts special symbols to dash (-
)- Symbols: , ; ' " ? # @ & = + * % ( ) @ : ! [ ] { } | \ ^ $
translate
: Transliterates non-English characters to their English equivalents.slug
: Converts spaces and other special characters to hyphens, making URLs SEO-friendly.trim
: Removes leading and trailing hyphens from the path.encode
: Encodes characters to URL-encoded
- default:
throwError
(Boolean): throw error insted returning{pathname:null}
- default:false
Return Value
- Object: An object containing the following properties:
pathname
(String): The normalized pathname of the URL.query
(Object): An object representing the query parameters of the URL.hash
(String): The hash fragment of the URL.
If the URL path is invalid or cannot be processed, the function returns an object with pathname
set to null
and error.
Error Handling
The function allows users to choose their preferred method of error notification. If throwError
is set to true, the function will throw a descriptive error when encountering an invalid URL path. Otherwise, it will return an object with pathname
as null
, which should be checked in the calling code.
Examples
Basic usage:
normalizeUrlPath('/test?param=1#section')
// {pathname:'/test',query:{ param: '1' },hash:'#section'}
normalizeUrlPath('/../test').pathname
// '/test'
normalizeUrlPath('/test/..').pathname
// '/'
normalizeUrlPath('\\test\\path').pathname
// '/test/path'
normalizeUrlPath('/test//path').pathname
// '/test/path'
normalizeUrlPath('/Test/Path',{lower:true}).pathname
// '/test/path'
normalizeUrlPath('/test&url/some.html?k=v&k1=v1').pathname
// '/test&url/some.html'
normalizeUrlPath('').pathname
// '/'
normalizeUrlPath('///').pathname
// '/'
normalizeUrlPath('/path-with-@-symbol').pathname
// '/path-with-@-symbol'
normalizeUrlPath('/path-with-semicolon;').pathname
// '/path-with-semicolon;'
normalizeUrlPath('/TeSt/MiXeDcAsE').pathname
// '/TeSt/MiXeDcAsE'
normalizeUrlPath('http://example.com:8080/test').pathname // null
Normalize with params:
const params1 = {lower: true, translate: true, slug: true, trim: true}
const slug = normalizeUrlPath('Hello, World!',params1).pathname;
// '/hello-world'
const url = 'some/url/with?query=string&unsafe=chars';
const { pathname, query } = normalizeUrlPath(url);
// { pathname:'/some/url/with', query:{ query: 'string', unsafe: 'chars' } }
normalizeUrlPath('/test-url-', {trim: true}).pathname
// '/test-url'
normalizeUrlPath('/test%20url',{encode:true}).pathname
// '/test%20url'
normalizeUrlPath('/test/path with spaces',{encode:true}).pathname
// '/test/path%20with%20spaces'
normalizeUrlPath('/привет',{encode:true}).pathname
// '/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82'
Normalize another language:
normalizeUrlPath('Café', {translate: true}).pathname;
// '/Cafe'
normalizeUrlPath('/こんにちは',{translate: true}).pathname
// '/konnitiha
normalizeUrlPath('/안녕하세요', {translate: true}).pathname
// '/annyeonghaseyo'
normalizeUrlPath('/спасибо', {translate: true}).pathname;
// '/spasibo'