When reading time from the backend database, the entire date, year, month, day, including hour, minute and second will be often taken, such as 2015-1-28 14:56:00, but generally we only need the previous year, month and day. A simple method can be used to intercept with spaces by split(" ")[0] to obtain the first paragraph of intercepting, which is the year, month and day we want. Now let’s talk about how to implement it with regular expressions.
Idea: Get the spaces in the string, and then replace all the spaces and characters after the spaces with empty ones.
Get the regularity of spaces as /s
practice:
The code copy is as follows:
var date = "2015-12-26 15:22:00";
console.log(date.replace(//s*/g,''));
But the result is 2015-12-2615:22:00. Only the spaces were removed, but the characters after the spaces were not removed. Then we will change our regularity.
The code copy is as follows:
var date = "2015-12-26 15:22:00";
console.log(date.replace(//s[/x00-/xff]*/g,''));
The result I got now is 2015-12-26, which meets the requirements.
This is because [/x00-/xff] will match double-byte characters, letters and Chinese characters will be matched, while separate writing /s will only match spaces.
This article is mainly to make everyone more familiar with the rules, and I hope you like it.