Insert '-' between every 6 characters

Viewed 119

I'm trying to make the text of an input be formatted by dividing the 48 numbers into blocks of 6 numbers, for example:

00000000000000000000000000000000000000000000 

becomes

000000-000000-000000-000000-000000-000000-000000-000000

These numbers are returned with a $response after submitting a form with CURL.

For some reason when the result returns it is not in this format, I need to erase a number and rewrite it so that it is corrected and in the correct format.

This is the code I'm using:

JS

$(window).on("load",
    function () {
        $("#resID").on("change paste input", function (e) {
            var t = this.value.replace(/\D/g, "");
            48 == t.length ? (this.value = t.match(new RegExp(".{1," + t.length / 6 + "}", "g")).join("-")) : (this.value = t)
        });
    });

HTML

<div class="response">
   <?php if($response != ''){ ?>
    <input type="search" class="form-control" id="resID" style="text-align: center;" value="<?php echo $response; ?>" data-clipboard-target="#resID" href="#" readonly>
    <?php } ?>
</div>

In short, it is formatting correctly but I need to update the numbers by deleting the last one and typing it in again.

Does anyone know what to be wrong?

2 Answers

This can be done in one line. We can use String.prototype.match() to split the string into an array of segments of 6 characters and Array.prototype.join() to concatenate these parts together.

var value = '000000000000000000000000000000000000000000000000';
console.log(value.match(/.{1,6}/g).join("-"))

In your case:

$(window).on('load', () => {
  $("#resID").on("change paste input", function(e) {
    this.value = this.value.match(/.{1,6}/g).join("-");
  })
})




/* below for demonstration purposes only */
setTimeout(() => {
  console.log('set value to 000000000000000000000000000000000000000000000000');
  $('#resID').val('000000000000000000000000000000000000000000000000').trigger('change');
}, 1000);
input {
  width: 415px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" class="form-control" id="resID" style="text-align: center;" value="" data-clipboard-target="#resID" href="#" readonly>

Using the substring in a for loop you can use the index to create a divisible section, the index, index + 6, push this into an array to get the parts that can be joined using the dash.

let string = "000000000000000000000000000000000000000000000000";

function addDashes(string) {
  let strArr = []
  for (let i = 0, len = string.length; i < len; i += 6) {
    strArr.push(string.substring(i, i + 6));
  }
  return strArr.join('-')
}

console.log(addDashes(string))

Related