![](/img/trans.png)
[英]How do I extract the title value from a string using Javascript regexp?
[英]How to extract a date value from a string using regexp in javascript?
我有一个像这样的字符串:
var value = "/Date(1454187600000+0300)/"
-从这开始,我需要一个类似1/30/2016
年1月30日的日期格式-为此,我正在尝试这样:
var value = "/Date(1454187600000+0300)/" // i need to fetch from here.
var nd = new Date(1454187600000); //this is static.
var month = nd.getUTCMonth() + 1; //months from 1-12
var day = nd.getUTCDate();
var year = nd.getUTCFullYear();
newdate = month + "/" + day + "/" + year;
console.log( newdate ); //works fine
但是我不知道如何使用正则表达式从value
变量中获取数字。 有人帮我吗?
您可以使用捕获组提取所需的日期部分:
nd = new Date(value.match(/\/Date\((\d+)/)[1] * 1);
//=> Sat Jan 30 2016 16:00:00 GMT-0500 (EST)
在这里/\\/Date\\((\\d+)/)[1]
将为您提供"1454187600000"
而* 1
会将该文本转换为整数。
如果要提取该数字,则不需要正则表达式,只需拆分字符串“ / Date(1454187600000 + 0300)/”示例:“ /Date(1454187600000+0300)/".split('+') [0],分裂( '(')[1]
一对捕获组将为您提供数字(可以将字符串转换为数字),但是随后您需要调整该数字以考虑时区,然后再将其传递给new Date
,使用两次捕获即可轻松实现。 看评论:
var value = "/Date(1454187600000+0300)/"; // Get the parts var parts = /^\\/Date\\((\\d+)([-+])(\\d{2})(\\d{2})\\)\\/$/.exec(value); // Get the time portion as a number (milliseconds since The Epoch) var time = +parts[1]; // Get the offset in milliseconds var offset = (+parts[3] * 3600 + +parts[4] * 60) * 1000; // Apply the offset if (parts[2] == "+") { // The timezone is `+` meaning it's *ahead* of UTC, so we // *subtract* the offset to get UTC time -= offset; } else { // The timezone is `-` meaning it's *behind* UTC, so we // *add* the offset to get UTC time += offset; } // Get the date var dt = new Date(time); document.body.innerHTML = dt.toISOString();
正则表达式/^\\/Date\\((\\d+)([-+])(\\d{2})(\\d{2})\\)\\/$/
是:
^
-输入开始 \\/
-文字/
Date
-文字文本Date
\\(
-文字(
(\\d+)
-一个或多个数字的捕获组; 这是为了大数目 ([-+])
-偏移量符号的捕获组, -
或+
(\\d{2})
-恰好两位数的捕获组; 这是抵消的小时部分 (\\d{2})
-另外两个数字的捕获组; 这是偏移量的分钟部分 \\)
-文字)
\\/
-文字/
$
-输入结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.