使用 JavaScript 分割字符串
下面的代码对我有用,但似乎很冗长。我可以缩短它吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要的只是
startTime
和endTime
吗?如果是这样,您可以对冒号字符执行split()
:Is all you want the
startTime
andendTime
? If so, you could just dosplit()
on the colon character:虽然正则表达式通常杀伤力太大,但它们会帮助您寻求更短的代码:
在 http://jsfiddle.net 上运行它/jvs3s/
While regexes are often overkill, they will help you here in your quest for shorter code:
Run it at http://jsfiddle.net/jvs3s/