Regexp.test call beeinflusst die nachfolgende String.MatchAll [Duplikat]JavaScript

Javascript-Forum
Anonymous
 Regexp.test call beeinflusst die nachfolgende String.MatchAll [Duplikat]

Post by Anonymous »

Ich fand ein seltsames Verhalten mit regulären JavaScript -Ausdrücken in meinem VueJS -Projekt. Was ist noch ein Fremder, nicht alle Übereinstimmungen fehlen, nur einige. class = "snippet-code-js Lang-js hübschesPrint-override">

Code: Select all

const DurationUnits = ['w', 'week', 'weeks', 'd', 'day', 'days', 'h', 'hour', 'hours', 'm', 'minute', 'minutes', 's', 'second', 'seconds', 'ms', 'millisecond', 'milliseconds', 'μs', 'microsecond', 'microseconds', 'ns', 'nanosecond', 'nanoseconds', 'ps', 'picosecond', 'picoseconds', 'fs', 'femtosecond', 'femtoseconds', 'as', 'attosecond', 'attoseconds', 'zs', 'zeptosecond', 'zeptoseconds', 'ys', 'yoctosecond', 'yoctoseconds', 'rs', 'rontosecond', 'rontoseconds', 'qs', 'quectosecond', 'quectoseconds']

// sort units longest first in order to correctly match 500ms as milliseconds (ms), not minutes (m)
const DurationUnitsSorted = [...DurationUnits].sort((a,b) => b.length-a.length)

const DurationRegexp = new RegExp(`(?\\d+(\\.\\d+)?)(?${DurationUnitsSorted.join('|')})`, 'g')

function parseDurationWithoutTest(duration) {
if (typeof duration !== 'string') {
console.warn('[parseDuration]', 'Invalid duration argument:', duration)
return []
}

return duration.matchAll(DurationRegexp).toArray()
}

function parseDurationWithTest(duration) {
if (typeof duration !== 'string' || !DurationRegexp.test(duration)) {
console.warn('[parseDuration]', 'Invalid duration argument:', duration)
return []
}

return duration.matchAll(DurationRegexp).toArray()
}

// works
const matchWithoutTest1 = parseDurationWithoutTest('123ns')
console.log('without test', matchWithoutTest1.map(o => o[0]))
const matchWithoutTest2 = parseDurationWithoutTest('1d 23h 30m 59s 500ms 123ns')
console.log('without test', matchWithoutTest2.map(o => o[0]))

// does not work
const matchWithTest1 = parseDurationWithTest('123ns')
console.log('with test', matchWithTest1.map(o => o[0]))
const matchWithTest2 = parseDurationWithTest('1d 23h 30m 59s 500ms 123ns')
console.log('with test', matchWithTest2.map(o => o[0]))

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post