1

I'm trying to write some js that will allow me to remove any colons and dashes in a string, then add a full stop after every 4th character, but not at the end of the string.

So for example xx:xx-xx-xx-xx:xx would become xxxx.xxxx.xxxx

I'm not the greatest with js but I've been able to write some code that gets rid of the colons and dashes, but I'm now a bit stuck with adding the full stops. THis is what I have so far:

<form>
Input: <input type="text" id="mac" name="macAddress">

<button onclick="convert(); return false;">Convert</button>

    <div id="outputDiv"></div>

</form>


<script type="text/javascript">

function convert() {

        var mac = document.getElementById('mac').value;
        var mac2 = mac.replace(/\:|-/g,"");

        document.getElementById("outputDiv").innerHTML= mac2;

};


</script>

I've had a look around at similar topics, I recon I might be able to put something together that would add the full stops but I'm not sure how I would stop it from adding one at the end of the string. Would really appreciate it if someone could point me in the right direction.

4 Answers 4

2

try

mac2 = mac2.replace(/(.{4})(?!$)/g , '$1.');

(.{4}) .(dot) is any character, and {4} means exact 4 times of any characters

(?!$) is assertion to match not followed by $, where $ is ending

/......../g use g to make it global replace

'$1.' $1 is backreference of content in the first ( )

0
1

You could use a negative lookahead to avoid putting the dot at the end of the string:

"xx:xx-xx-xx-xx:xx".replace(/[:-]/g,"").replace(/(.{4})(?!$)/g, "$1.")
// xxxx.xxxx.xxxx
0

Try that:

function convert(mac) {
    mac = mac.replace(/\:|-/g,"");
    mac = mac.replace(/(....)(?!$)/g, "$1.");
    console.log(mac);

    return mac;
}
0

Use match on a string to split it to an array, and then join on the array:

str = "12345678abcdefgj"
arr = str.match(/.{1,4}/g)
// arr == ["1234", "5678", "abcd", "efgj"]
arr.join('.')
// "1234.5678.abcd.efgj"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.