Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery Regex Replace Input Field with Valid Characters

I am building a CMS where a user can customize the SEO URL of a page via a text input control. For example, say the user is creating a gallery, and they want their page to be accessed at http://www.example.com/my-1st-gallery.

Notice how the "my-1st-gallery" portion doesn't contain any illegal characters for a URL. Since most users won't know what is allowed and not allowed, I'd like to create a JavaScript regex filter which can filter/convert all illegal characters on key-up.

I know how to use jQuery/JavaScript to listen for key-up events, but I'm not sure how to use a regex to do the following:

  1. Filter all characters other than a-z, A-Z, 0-9, a "-", a "_", and a space.
  2. Change any "_" and spaces to a "-", and let the user know that the given character has been converted into "-".

Could someone provide a good example of how to do the regex part. Again, I understand how to listen for key-up events.


Ok, with all of these good answers, I think I can piece this together for my web app. I wish I could select more than one answer as my final! :S Thank you all!

like image 930
Oliver Spryn Avatar asked Dec 13 '22 11:12

Oliver Spryn


2 Answers

$("#inputElement").keyup(function() {
    var input = $(this),
    var text = input.val().replace(/[^a-zA-Z0-9-_\s]/g, "");
    if(/_|\s/.test(text)) {
        text = text.replace(/_|\s/g, "");
        // logic to notify user of replacement
    }
    input.val(text);
});
like image 130
jdc0589 Avatar answered Dec 14 '22 23:12

jdc0589


You could do something like this (asuming you have the character stored in the key variable)

if(key.test(/[_\s]/)){
   key = "-";
   alert("key changed to -");  
}
if(!key.test(/[a-zA-Z0-9\-]/g){
  key = "";
  alert("Invalid key");
}

Hope this helps. Cheers

like image 23
Edgar Villegas Alvarado Avatar answered Dec 15 '22 00:12

Edgar Villegas Alvarado