我正在使用slice()
分解字符串,但是无法正常工作。
字符串:
var datept = "2018-01-19"
var timept = "12:05"
不相交:
var month = datept.slice(5, -3); // should: "01" is: "01"
var day = datept.slice(8, -0); // should: "19" is: "" -- WRONG
var year = datept.slice(0, -6); // should: "2018" is: "2018"
var hours = timept.slice(0, -3); // should: "12" is: "12"
var minutes = timept.slice(3, -0); // should: "05" is: "" -- WRONG
还尝试了:
var day = datept.slice(-8, -0); // or
var day = datept.slice(8, -0); // or
var day = datept.slice(-8, 0); // or
var day = datept.slice(8, 0);
最佳答案
您可以分割日期,并使用destructuring assignment作为值。
var datept = "2018-01-19",
timept = "12:05",
[year, month, day] = datept.split('-'),
[hours, minutes] = timept.split(':');
console.log(year, month, day);
console.log(hours, minutes);
关于javascript - string.slice()无法按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48342693/