String methods are not my strong suit, I've been trying to manipulate an input field value that needs to be 24 characters long
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, "")
});
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.