Click here to Skip to main content
Click here to Skip to main content

Easy Manipulation of URL in JavaScript

, 23 Apr 2013
Rate this:
Please Sign up or sign in to vote.
Lightweight URL manipulation with JavaScript with pretty simple API. Minified and gzipped < 1KB

Introduction

I have been working as a web-developer for many years, I am bored with doing the same task again and again. What do you do when you need to modify some URL part, where URL is a simple string? It's possibly to do the trick with regular expression or in some other way, or try to search for some existing solution. By the way, I didn't find any good solution (because of weight or functionality) and am tired of this so much that I decided to write my own. The goal was to have a really simple, easy-to-use functionality with minimum code-base. Hope I was able to fit those requirements.

Using the Code

The code is available at Github and licensed under MIT license conditions. So feel free to use it anywhere and do what you want.

There is also a possibility to install it via JAM repository, simply as:

$ jam install jsurl 

Look at this simple example of using the library. It's really easy. First, you need just instantiate the Url object from string, then to use it as an object or as a string, depending on circumstances:

var u = new Url('http://user:pass@example.com:8080/some/path?foo=bar#anchor');
// NOTE: calling constructor without argument will refer to the current document's URL

// let's see what we have:
alert( 'Source URL is ' + u);

// let's change something:
u.hash = 'new-anchor';  // replace old anchor with new one
u.protocol = 'https';   // changing the protocol
u.pass = '';            // removing password
u.query.foo = 'baz';    // changing value of "foo" parameter in QueryString
u.query.bar = [1,2,3];  // adding new parameter "bar" to QueryString with multiple values

// let's see what we have now:
alert( 'New URL is ' + u);   

Points of Interest

During the development, I had used some ideas from Jan Walter about parsing QuerySring madness in JavaScript. That increased the size of the code-base, but solved some annoying problems.

I was totally focused on having this library without any external dependencies and that was done. So I just hope it will be useful to anyone else.

Please, don't hesitate to leave your feedback, comments and bug reports.

License

This article, along with any associated source code and files, is licensed under The MIT License

About the Author

Mikhus
Team Leader
Ukraine Ukraine
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140718.1 | Last Updated 23 Apr 2013
Article Copyright 2013 by Mikhus
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid