[英]What is the better way to split Date string in JavaScript?
I am getting from api xml data, where one of the xml elements is date time, which nodeValue is always in this format - string: "YYYY-MM-DD". 我从api xml数据获取,其中一个xml元素是日期时间,nodeValue始终采用这种格式 - 字符串:“YYYY-MM-DD”。 ( I can not request from api, to return me date time in diffrent format )
( 我无法从api请求,以不同格式返回日期时间 )
My problem is to split and convert this format into this string: "DD.MM.YYYY" 我的问题是将此格式拆分并转换为此字符串:“DD.MM.YYYY”
Basicly I did this: 基本上我这样做了:
var myString = "2015-04-10"; //xml nodeValue from time element
var array = new Array();
//split string and store it into array
array = myString.split('-');
//from array concatenate into new date string format: "DD.MM.YYYY"
var newDate = (array[2] + "." + array[1] + "." + array[0]);
console.log(newDate);
Here is jsfiddle: http://jsfiddle.net/wyxvbywf/ 这是jsfiddle: http : //jsfiddle.net/wyxvbywf/
Now, this code works, but my question is: Is there a way to get same result in fewer steps? 现在,这段代码可行,但我的问题是:有没有办法以更少的步骤获得相同的结果?
should do the same 应该这样做
var newDate = '2015-04-10'.split('-').reverse().join('.')
// ^ ^ ^ join to 10.04.2015
// | |reverses (2 -> 0, 1 -> 1, 0 -> 2)
// | delivers Array
您可以使用具有捕获组的正则表达式,并使用String.prototype.replace
重新格式化它。
var newDate = myString.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3.$2.$1');
是。
var newDate = '2015-04-10'.split('-').reverse().join('.');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.