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.
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.
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 az or AZ 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;
从字符串中删除冒号和空格只需使用
str = str.replace(/[:\s]/g, '');
HTML
<input type="text" id="macaddress"/>
<button onclick="removeChar()">Click me!</button>
JS
function removeChar() {
var a = document.getElementById("macaddress").value.trim();
a = a.split('');
a.forEach(function (character, index) {
if (character === ':') {
a.splice(index, 1);
}
});
a = a.join('');
document.getElementById("macaddress").value = a;
}
Your Regex searches for "colon immediately followed by space".
If you add a pipe in between them: /:| /
/:| /
, then it will search for all colons and/or spaces, in any order.
Demo:
function removeChar() { var a = document.getElementById("macaddress").value; a = a.replace(/:| /g, ''); document.getElementById("result").innerHTML = a; }
<input type="text" id="macaddress" onChange="removeChar();" /> <div id="result"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.