Durgaprasad Budhwani
Durgaprasad Budhwani

Reputation: 977

JavaScript RegEx to replace repeat characters of more than 2

I have an string, like YYYY/MMM/DD and I want to convert it into YY/MM/DD formart. In short, I want to replace repeated characters more than 2.

Example 01:- YYYY/MMM/DD -> YY/MM/DD Example 02 :- MMM/YYYY/DD -> MM/YY/DD

Please help me out.

Upvotes: 2

Views: 1219

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173572

This should do it, using back references to find sequences of 3+ the same character and then replacing them with just two:

str.replace(/(.)\1{2,}/g, '$1$1')

Upvotes: 4

111
111

Reputation: 1779

try to use this

    var date = new Date();
    var datestr = ('0' + date.getDate()).substr(-2, 2) + '/' + ('0' + date.getMonth()).substr(-2, 2) + '/' + ('0' + date.getFullYear()).substr(-2, 2);
    alert(datestr);

Upvotes: -1

Related Questions