Clean URL Generator

From Codevault

Jump to: navigation, search

This function generates clean URL's, similar to how Wordpress generates URL's from the title tag. I didn't like how WP requires you to click the edit link to change the URL, however.

The number 40 used in both forms represents the max length of the URLs you would like to use. In my particular CMS, the max length is 40, hence the value.

How it works is the user types in a human readable title in the title field, such as "I am a cool title.", and tabs out or clicks out of the field. When this happens, we activate the onblur event for the title field. This then fires the url_friendly function using the value we have typed in the field. In url_friendly(), we replace all spaces with underscores, make everything lowercase, get rid of excess characters and anything not a letter or number. We then return the value and this gets written into the url input field.

HTML

<script src="url_friendly.js" language="Javascript"></script>
<input type="input" name="title" value="" onblur="this.form.url.value = url_friendly(this.value)" maxlength="100" />
<input type="input" name="url" value=""  maxlength="40" />


url_friendly.js

function url_friendly(text) {	
  var url = text
    .toLowerCase()
    .replace(/^\s+|\s+$/g, "")
    .replace(/[_|\s]+/g, "_")
    .replace(/[^a-z0-9_]+/g, "")
    .substring(0,40)
    .replace(/[_]+/g, "_")
    .replace(/^_+|_+$/g, "")
    ; 
    return url;
}
Personal tools