Cómo convertir una cadena de tiempo como 1m15s a 75s , 75 o 75000 idealmente usando momentjs .
Intenté analizar esa cadena usando new Date('1m1s') pero da Invalid Date .
No quiero recurrir a expresiones regulares:
const second = (function () { const countdownStep = '1h1m1s'.match( /(?:(?<h>\d{0,2})h)?(?:(?<m>\d{0,2})m)?(?:(?<s>\d{0,2})s)?/i ); return ( (countdownStep.groups.h ? parseInt(countdownStep.groups.h) * 3600 : 0) + (countdownStep.groups.m ? parseInt(countdownStep.groups.m) * 60 : 0) + (countdownStep.groups.s ? parseInt(countdownStep.groups.s) : 0) ); })();Puedes usar la interfaz de duración de momentjs:
let s = '1m15s'; // convert to duration format and pass to momentjs let secs = moment.duration('PT' + s.toUpperCase()).as("seconds"); console.log("seconds: ", secs); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>Sin biblioteca, podría ser:
const unit = { s: 1, m: 60, h: 60*60 }; let s = '1m15s'; let secs = s.toLowerCase().match(/\d+./g) .reduce((acc, p) => acc + parseInt(p) * unit[p.at(-1)], 0); console.log("seconds: ", secs);Intenté esto, ¿te es útil?
let d = '1H1s'; d = d.toLowerCase(); let sec = 0; if(d.indexOf('h') > -1) { if (d.indexOf('m') == -1) { d = d.substring(0, d.indexOf('h') + 1) +"0m"+d.substring(d.indexOf('h') + 1); } } let newDs = d.replace('h',':').replace('m',':').replace('s','').split(':'); newDs.forEach((v, i) => sec += Math.pow(60, (newDs.length - i - 1)) * v); console.log(sec);Otro enfoque usando js simple:
const getSecondsFromString = (str) => { const hourIndex = str.indexOf("h") const minuteIndex = str.indexOf("m") const secondIndex = str.indexOf("s") let hours = 0 let minutes = 0 let seconds = 0 if (hourIndex !== -1) { hours = Number(str.substring(0, hourIndex)) } if (minuteIndex !== -1) { if (hourIndex !== -1) { minutes = Number(str.substring(hourIndex + 1, minuteIndex)) } else { minutes = Number(str.substring(0, minuteIndex)) } } if (secondIndex !== -1) { if (minuteIndex !== -1) { seconds = Number(str.substring(minuteIndex + 1, secondIndex)) } else if (hourIndex !== -1) { seconds = Number(str.substring(hourIndex + 1, secondIndex)) } else { seconds = Number(str.substring(0, secondIndex)) } } return hours * 3600 + minutes * 60 + seconds }