Search code examples
javascriptstring

Forced string formatting to include dashes


String methods are not my strong suit, I've been trying to manipulate an input field value that needs to be 24 characters long

  • 21 of those characters are letters or numbers (no special characters other than dash)
  • 3 of those fields are dashes in the 3rd, 8th, and 17th place
  • I've got it working when 21 characters have been entered, but struggling to think through if a user adds more than 21 characters, or when a user add say, 30 characters, how do I only keep the first 21 entered & add dashes?

const caseNumberInput = document.querySelector(".theme--mobile #case_number");
caseNumberInput.addEventListener("blur", (e) => {
  //get rid of all special characters other than "-"
  const value = e.target.value.toUpperCase().replace(/[^a-zA-Z0-9 -]/g, "");
  const length = e.target.value.replace(/[^a-zA-Z0-9 -]/g, "").length;

  if (length === 21) {
    //if length is 21, add the dashes in the 3rd, 8th, and 17th places
    caseNumberInput.value = value.slice(0, 2)+ "-" + value.slice(2,6) + "-" + value.slice(6, 14)+ "-" + value.slice(14)
  }

  if (length >= 21) {
    //remove the dashes then add them back so I don't get multipe dashes if they are already existing / keep only 21 characters?
    let newValue = e.target.value.replace(/[^a-zA-Z0-9]/g, "").toUpperCase().slice(0, 21);
    newValue.slice(0, 2)+ "-" + temp.slice(2,6) + "-" + value.slice(6, 14)+ "-" + value.slice(14);
    caseNumberInput.value = newValue
    console.log(newValue)
  }

});

//keyup to remove any special characters except "-"

caseNumberInput.addEventListener('keyup', (e) => {
  e.target.value = e.target.value.toUpperCase().replace(/[^a-zA-Z0-9 -]/g, "")
});


Solution

  • It's usually done like this:

    const caseNumberInput = document.querySelector(".theme--mobile #case_number");
    
    caseNumberInput.addEventListener("blur", (e) => {
      // Get and sanitize input
      let value = e.target.value.toUpperCase().replace(/[^a-zA-Z0-9]/g, "");
    
      // Keep only the first 21 characters
      value = value.slice(0, 21);
    
      // Add dashes in the 3rd, 8th, and 17th positions
      const formattedValue = `${value.slice(0, 2)}-${value.slice(2, 7)}-${value.slice(7, 16)}-${value.slice(16)}`;
    
      caseNumberInput.value = formattedValue;
    });
    
    caseNumberInput.addEventListener('keyup', (e) => {
      // Sanitize input
      e.target.value = e.target.value.toUpperCase().replace(/[^a-zA-Z0-9 -]/g, "");
    });
    

    That is, filter, trim the extra characters, and then insert - in the right places. If you need to put dashes after 21 characters, you can compare value before and after slice and add the necessary number of dashes.