Need code explanation to split the string into separate digits

If you have a string of English digits “stuck” together, like this:

"zeronineoneoneeighttwoseventhreesixfourtwofive"
and you want to split the string into separate digits, you need to write code like

let s = 'zeronineoneoneeighttwoseventhreesixfourtwofive'
s = s.replace(/one|t[wh]|.i|[fsz]/g," $&");

I want explanation for this Regex line of code:

s.replace(/one|t[wh]|.i|[fsz]/g," $&");

Hi @abdulrahmanmhdanas, the regular expression matches the possible initial letters of the numbers:

expression numbers
one one
t[wh] two, three
.i five, six, eight, nine
[fsz] four, seven, zero

You might actually just write them out though, which would be way more readable:

/one|two|three|four|five|six|seven|eight|nine|zero/

Anyway, and the " $&" just prepends a space to that match (the $& is a replacement pattern substituted with the matched substring).

4 Likes

To be specific: It matches the possible initial letters of the numbers and avoids ambiguity between joined numbers.

IE:
Q: Why do we need to say “one”? why not just “o”?
A: Because “o” would put a space in the middle of “four”.
Q: Okay, but no other number has “on” in it, so we can match on that.
A: Except if you have a 0 followed by a 9, the string would read “zeronine”. This is the same reasoning why you cant search for “ne” either (seveneight), and must search for the full “one”.

EDIT: Actually “ne” gets removed by the first logic pattern, as “nine” contains ne. But you get the point.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.