javascript - 如何找到字符串中日期和时间的第一个索引

标签 javascript

我有一个 YYYY-MM-DD 日期格式的字符串。

var x = "I will need 2 pieces of that product 2020-01-16 04:38:09.After that i will need another 2020-01-16 04:38:09.";

我需要从 0 到第一个日期的开头对文本进行子串,因此整个字符串的输出应该是:

I will need 2 pieces of that product

老实说,因为我不知道 reg ex,所以我没有尝试任何事情。这就是我需要帮助的原因。 提前致谢

最佳答案

您可以使用正则表达式和组来实现此目的。
您可以注意到,我在这里使用了惰性运算符 ( *? ),这样,它只会匹配字符串的第一部分,即第一个日期。

^(.*?)(?:\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})

此正则表达式将匹配任何内容,直到看到日期格式 YYYY-MM-DD HH:mm:ss 。 比赛的第一组将是您正在寻找的。

在 Javascript 中,你可以像这样实现它:

let text = 'I will need 2 pieces of that product by 2020-11-26 2020-01-16 04:38:09.After that i will need another 2020-01-16 04:38:09.';
// notice here that we are using a non-capture group around the date
// because we do not need this part.
let regex = /^(.*?)(?:\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/;
let match = regex.exec(text);
// the first element of the array contains the whole matches,
// the second contains the first group.
console.log(match[1]);

关于javascript - 如何找到字符串中日期和时间的第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59770433/

相关文章:

javascript - 如何取消订阅 mobx-state-tree 中的 onSnaphot() ?

javascript - 优雅地处理电话 URL

javascript - 根据页面加载时选择的单选按钮显示某些字段

javascript - react 自定义组件(数据表)

javascript - 为什么我的 pg-query 结果抛出 TypeError

javascript - google.visualization.Calendar 中的对数色阶?

javascript - Bootstrap 确认图标未显示

javascript - 像选取框一样生成动画

php - 将变量从 javascript 传递到 php get 语句

javascript - 替换 JavaScript 中所有出现的字符串不起作用