When entering 4 digits, you need to make a substitution and set a slash between the second and third digits. For example, I enter 1225 - I need get 12/25
changeInput(event) {
this.setState({ [event.target.name]: event.target.value.replace(/\/?/g, '').replace(/(\d{2})/, '$1/') });
}
<input type="text" inputMode="numeric" id="cardDate" name="cardDate" value={this.state.cardDate} autoComplete="off" maxLength="5" placeholder="MMYY" onChange={this.changeInput.bind(this)} />
I wrote a replacement code, but when I try to edit the input field, there is a problem. What's wrong?
Using Regex for this is a little bit overkill, there are a few ways to do this: First, using String.prototype:
String.prototype.insert = function (index, string) {
if (index > 0) {
return this.substring(0, index) + string + this.substr(index);
}
return string + this;
};
const string = "1234";
const substring = string.insert(2, "/");
console.log(substring) // "12/34"
You can do it through an array too:
function replaceAt(string, index, toInsert) {
const substring = [...string];
substring.splice(2, 0, toInsert);
return substring.join("");
}
const string = "1234";
const replaced = replaceAt(string, 1, "/");
console.log(replaced);