Thursday, February 12, 2009

Automatic and Dynamic Title URLs from Titles using Javascript

This is a handy little javascript snipplet that will convert text in one text field to url friendly text in another.  This is very useful if you're trying to automatically create title URLs from the title of your post.  This helps with search engine optimization by giving you friendly URLs.  Below is the javascript and a test form.  You can copy it all, paste it, and test it.

<html>
<head>
<script type="text/javascript">
function urltitle(title)
{


// Create the url friendly title
var url = title
.toLowerCase() //change everything to lowercase
.replace(/^\s+|\s+$/g, "") //trim leading and trailing spaces
.replace(/[&]+/g, "and") //replace ampersand
.replace(/[#]+/g, "sharp") //replace pound
.replace(/[@]+/g, "at") //replace at
.replace(/[%]+/g, "percent") //replace percent
.replace(/[+]+/g, "plus") //replace plus
.replace(/[-|\s]+/g, "_") //replace spaces and hyphens to underscore
.replace(/[^a-z0-9_]+/g, "") //remove all non-alphanumeric characters except the underscore
.replace(/[_]+/g, "_") //remove duplicate underscores
.replace(/^_+|_+$/g, "") //trim leading and trailing underscores
;
document.getElementById('title_url').value = url;
}
</script>
</head>
<body>


<input type="text" onkeyup="javascript:urltitle(this.value);" />
<input type="text" id="title_url" />


</body>
</html>


As we usually give credits for what we find, this is where we got the original script before modifying it: Rewrite input to friendly URL

No comments: