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:
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!
$("#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);
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With