Clicky

Once again I want to talk about URLs and who doesn’t know that I’m a big fan of friendly, clean and pretty URLs in my applications! When you write an application (for example a blog engine) you have multiple choices to create unique URL for a single post; you can include an integer ID (myblog.com/458) or a GUID instead of integer or the best way, a friendly URL like myblog.com/hey-i-am-a-clean-url. This value should be unique and should not be changed if your blog post title is changed; so we should have a separate column in our database table to store this friendly URL. I wrote a simple JavaScript code that receives your blog post title, clean it from non alphanumeric characters and replaces them with a dash, change all characters to lower case and make it ready to be sent to your business logic handler:

<script type="text/javascript" language="javascript">
    function parseUrl(url) {
        var cleanUrl = (url + " ").replace(/[^a-zA-Z0-9]+/g, "-");
        return cleanUrl.slice(0, cleanUrl.length -1).toLowerCase();
</script>

and this two lines of code to fill URL field automatically as user types the post title (using jQuery:

<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        $("#postTitle").keyup(function() { $("#postUrl").val(parseUrl($("#postTitle").val())) }
        );
    });
</script>

 

This is very useful if you’re building applications using ASP.NET MVC and have control over URLs using routing engine. This is also helpful for WebForms developers who use routing in WebForms or rewrite extension less URLs using IIS7, ISAPI_REWRITE and etc.

Let your URLs be more friendly against search engines ;)

kick it on DotNetKicks.com


 
Comments are closed.