Regex in javascript

Asked

Viewed 32 times

1

How would a regex take only numbers and / in a string.

Example: Start date: 08/29/2016

Result: 08/29/2016

2 answers

1

According to that question on Stack Overflow, the suggested simple way is:

/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/

But this expression as (reported in a comment) of response is not correct for February 29,

another users suggested the following expression:

var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;

That although it’s much more complex is the one I’ve been using, I’ve never found errors in it.

In the same question you will find valid ways to date through functions instead of using regex, if it is more interesting to you, why not?

1

You can do it like this:

var data1 = "Data de inicio: 29/08/2016";
var data2 = data1.replace(/[^0-9/]/g, '');
document.write(data2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.