使用 JavaScript 分割字符串

发布于 2024-12-20 12:48:36 字数 415 浏览 0 评论 0原文

下面的代码对我有用,但似乎很冗长。我可以缩短它吗?

var str = "some title of an event here, weekday 17:00 – 18:00 o’clock, with name of a person";
var date = str.split(', ');
var time = date[1].split(' ');
var timeItems = time[1].split('–');
var startTime = timeItems[0].trim();
var endtime = timeItems[1].trim();
alert("event lasts from "startTime + " to " + endtime);

谢谢

the following code works for me, but seems to be quite long-winded. Can i shorten it?

var str = "some title of an event here, weekday 17:00 – 18:00 o’clock, with name of a person";
var date = str.split(', ');
var time = date[1].split(' ');
var timeItems = time[1].split('–');
var startTime = timeItems[0].trim();
var endtime = timeItems[1].trim();
alert("event lasts from "startTime + " to " + endtime);

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

非要怀念 2024-12-27 12:48:36

您想要的只是 startTimeendTime 吗?如果是这样,您可以对冒号字符执行 split()

times = str.split(':');
startTime = times[0].slice(-2) + ':' + times[1].slice(0,2);
endTime = times[1].slice(-2) + ':' + times[2].slice(0,2);
alert("event lasts from " + startTime + " to " + endTime);

Is all you want the startTime and endTime? If so, you could just do split() on the colon character:

times = str.split(':');
startTime = times[0].slice(-2) + ':' + times[1].slice(0,2);
endTime = times[1].slice(-2) + ':' + times[2].slice(0,2);
alert("event lasts from " + startTime + " to " + endTime);
孤寂小茶 2024-12-27 12:48:36

虽然正则表达式通常杀伤力太大,但它们会帮助您寻求更短的代码:

var str = "some title of an event here, weekday 17:00 – 18:00 o’clock, with name of a person";
var times = str.match(/\d\d?:\d\d/g);
alert("event lasts from " + times[0] + " to " + times[1]);

http://jsfiddle.net 上运行它/jvs3s/

While regexes are often overkill, they will help you here in your quest for shorter code:

var str = "some title of an event here, weekday 17:00 – 18:00 o’clock, with name of a person";
var times = str.match(/\d\d?:\d\d/g);
alert("event lasts from " + times[0] + " to " + times[1]);

Run it at http://jsfiddle.net/jvs3s/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文