the Forum

Converting Strings to URL-friendly strings using jQuery

Posted on February 13, 2012 by Michael Rosario
Total Posts: 33  |  Join date: 03-12-11

I needed a form field that converts a string to a URL-friendly field. So first I created two input fields:
<input class="TxtInput" type="text" name="screen_name" value="" id="screen_name" class="TxtInput" /> 
<
input class="TxtInput" type="hidden" name="user_url" readonly='readonly' value="{user_url}" id="user_url" class="TxtInput" /> 
Then I used jQuery to automatically store the cleaned aka "sanitized" value of user_url automatically. Here is my code:
/* This is for loading */
var temp = $("#screen_name").val().toLowerCase().replace(/ +/g,'_').replace(/[0-9]/g,'').replace(/[^a-z0-9-_]/g,'').trim();
$(
'#user_url').val(temp);

/* This is when the user updates the input field */
$("#screen_name").change(
function()
{
var temp = $(this).val().toLowerCase().replace(/ +/g,'_').replace(/[0-9]/g,'').replace(/[^a-z0-9-_]/g,'').trim();
$(
'#user_url').val(temp);
}); 
So for example, I put John Jameson Smith on screen_name field. On the user_url field, it gets john_jameson_smith.

Tags: There are no tags for this entry.

There are no answers yet.  Add yours below.

add your answers here
comments powered by Disqus