Remove punctuation from string using Javascript

I’m a morning person, and my mind is usually sharpest on Monday or Tuesday mornings, so these are the best times for me to work on fiddly javascript stuff. Today was one of those mornings and here are the results, just in case I want to refer back to them later on.

I had many items dotted around an Apex application where the user is allowed to enter “Codes” – values that must be uppercase and contain no spaces or other punctuation characters – except underscores (_) were allowed.

To make things easier for the user, I wanted the page to automatically strip these characters out when they exit the field, instead of just giving validation errors (Note: I still included the validations, but the javascript just makes the process a bit smoother for the user doing the data entry).

My APEX application already has a global .js file that is loaded with each page, so all I had to do was add the following code to it:

function cleanCode (c) {
  return c.replace(/[^A-Za-z0-9_]/g,"");
}

$(document).ready(function() {

  //automatically remove non-code characters from
  //"edit_code" class
  $( document ).on('change', '.edit_code', function(){
    var i = "#"+$(this).attr("id");
    $(i).val( cleanCode($(i).val()) );
  });

});

EDIT: greatly simplified regexp based on the excellent contribution by Jacopo 🙂
EDIT #2: corrected, thanks to Sentinel

Finally, on each “Code” page item, I set the following attribute (or append, if other classes have already been added):

HTML Form Element CSS Classes = edit_code

For code items within a tabular form, I set the following column attribute:

Element CSS Classes = edit_code

Static File not updating in runtime APEX environment
APEX CSV Import: “Data Loading Failed”

Comments

  1. Jacopo Galati
    13 July 2015 - 1:36 pm

    /[^A-z0-9_]+/g should do the same, if I understood well

    • Thanks Jacopo, that’s much better! I’ve updated the article accordingly.

    • Won’t A-z include the following characters []^_' least wise my ASCII table shows those 6 characters fall between Z and a.

      • Thanks Sentinel, you’re right. It should be .replace(/[^A-Za-z0-9_]/g,"")

  2. \W
    Matches any non-word character. Equivalent to [^A-Za-z0-9_].
    For example, /\W/ or /[^A-Za-z0-9_]/ matches ‘%’ in “50%.” -MDN docs

Leave a Reply

Your email address will not be published / Required fields are marked *