Remove special characters from input field
Solution 1
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.
Solution 2
If you want to keep only numbers and letts you can use this
a.replace(/[^a-zA-Z0-9]/g, '');
which basically replaces everything that isn't a-z or A-Z or 0-9 with an empty string.
A great tool for explaining regex and testing it is Regex101
And this line document.getElementById.innerHTML = a;
should be fixed as well, you probably meant something like document.getElementById('some-elements-id').innerHTML = a;
Solution 3
to remove colons and spaces from string simply use
str = str.replace(/[:\s]/g, '');
Michael
Updated on June 04, 2022Comments
-
Michael almost 2 years
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.-
HoldOffHunger over 5 yearsYou have your regex as ": ", it should be ":" (no spaces). See: stackoverflow.com/a/6525002/2430549
-
HoldOffHunger over 5 yearsPossible duplicate of Replacing a colon using string replace using Javascript and jQuery
-
-
AwesomeGuy over 5 yearsWhy do you suggest him to remove the last line, he probably needs it, just needs to fix it.
-
Michael over 5 yearsPerfect the trim worked. I had to combine it with my first function to pull the data but it worked. Thank you
-
Cristian Sepulveda over 4 years
<input type="text" onkeyup="this.value = this.value.replace(/[^a-z0-9_-]/g, '')" >
works for me.