Home > Web Front-end > JS Tutorial > body text

JavaScript uses regular expressions to remove characters after spaces_javascript skills

WBOY
Release: 2016-05-16 16:13:58
Original
1575 people have browsed it

When reading time from the back-end database, we often get the entire date, year, month, and day including hours, minutes, and seconds, such as 2015-1-28 14:56:00, but generally we only need the previous year, month, and day. That's it. A simple method is to directly use split(" ")[0] to intercept with spaces, and get the first intercepted paragraph, which is the year, month and day we want. Now let's talk about how to use regular expressions to achieve it.

Idea: Get the spaces in the string, and then replace all the spaces and characters after the spaces with empty spaces.

The regular rule for getting spaces is s

Practice:

Copy code The code 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 are removed, but the characters after the spaces are not removed. Next, let’s change our regular expression.

Copy code The code is as follows:

var date = "2015-12-26 15:22:00";
console.log(date.replace(/s[x00-xff]*/g,''));

The result now is 2015-12-26, which meets the requirements.

This is because [x00-xff] will match double-byte characters, letters and Chinese characters, while writing s alone only matches spaces.

This article is mainly to make everyone more familiar with regular rules. I hope you will like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!