javascriptregexspecial-charactersonchange

Remove special characters from input field


I've been searching everywhere but have been unable to find exactly what I am looking for.

I have an html form that is filled out with Mac addresses from our inventory so the strings inputted into the input field will look like:

A1:A2:A3:A4:A5:A6

I'm trying to write a script to remove the : character plus any spaces anywhere. That way when it is entered the output will be:

A1A2A3A4A5A6

This is what I have so far:

<input type="text" id="macaddress" onChange="removeChar();WriteLog();" />

Then in my script I have:

function removeChar() {
  var a = document.getElementById("macaddress").value;
  a = a.replace(/: /g, '');
  document.getElementById.innerHTML = a;
}

I don't get any JavaScript errors with this but nothing happens.

I also have another script that pulls the value of the field into a work log which is the other function WriteLog().

Essentially I want to remove the : then have the new value pulled into the log by the second function.


Solution

  • Question spec says you want to remove : and : with space. Make the space in the regex optional:

    a = a.replace(/:( )?/g, '');

    But you also need to account for preceeding spaces:

    a = a.replace(/( )?:( )?/g, '');

    I would also trim the initial string (Just good practice)

    a = a.trim().replace(/( )?:( )?/g, '');

    Finally, I am not sure what this line does: document.getElementById.innerHTML = a;, but that line will throw an error. Remove it.