使用JavaScript拆分字符串

使用JavaScript拆分字符串,javascript,arrays,string,split,trim,Javascript,Arrays,String,Split,Trim,下面的代码对我来说很有用,但似乎很冗长。我可以缩短它吗 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

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

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);

谢谢

这就是你想要的
开始时间
结束时间
?如果是这样,您可以对冒号字符执行
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);

虽然正则表达式通常是多余的,但它们可以帮助您在这里寻找更短的代码:

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]);

运行它如果它按预期工作,则无需修复。继续:)