Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
ReactJS - replace / expire date card

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!