Home  >  Article  >  Web Front-end  >  javascript使用正则表达式实现去掉空格之后的字符_javascript技巧

javascript使用正则表达式实现去掉空格之后的字符_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:13:581527browse

从后端数据库读取时间时,经常会把整个日期年月日包括时分秒都取到,如2015-1-28 14:56:00,但是一般的我们只需要前面的年月日就行了.一个简单的方法,直接用split(" ")[0]就可以以空格截取,获得截取的第一段,就是我们要的年月日.现在来说说用正则表达式怎么实现.

思路:获取到字符串中的空格,然后把空格及空格后的字符全部替换为空.

获取空格的正则为\s

实践:

复制代码 代码如下:

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

但是得到的结果是2015-12-2615:22:00,仅仅去掉了空格,但是没有去掉空格后面的字符,接着来改我们的正则.

复制代码 代码如下:

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

现在得到的结果就是2015-12-26,符合要求.

这是因为[\x00-\xff]会匹配双字节字符,字母和汉字都会被匹配出来,而单独的写s只匹配了空格.

本文主要是为了让大家更加的熟悉正则,希望大家能够喜欢。

Statement:
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