Skip to content
Advertisement

JavaScript Regex to capture repeating part of decimal

Looking for the best way to take an arbitrary number with potentially repeating decimal part, and discover the repeating part (if present).

Ultimately, I need to decorate the number with overline notation (either with css text-decoration or MathML mline), so I need to know the index of where the repetition begins also.

So I need regex that will get me (or can be used in an algorithm to get) the following results:

1.333 // result: {"pattern": 3, index: 0}
1.5444 // result: {"pattern": 4, index: 1}
1.123123 // result: {"pattern": 123, index: 0}
1.5432121212 // result: {"pattern": 12, index: 4}
1.321 // result: null
1.44212 // result: null

Additional Example (from comments):

1.3333 // result: { "pattern": 3, index: 0}

Advertisement

Answer

function getRepetend(num) {
    var m = (num+'').match(/.(d*?)(d+?)2+$/);
    return m && {pattern: +m[2], index: m[1].length};
}

It works like this:

  • First, convert the number to string in order to be able to use regular expressions.
  • Then, match this regex: /.(d*?)(d+)2+$/:
    • . matches the decimal dot.
    • (d*?) matches the digits between the decimal dot and the repetend, and captures the result into backreference number 1.
    • (d+?) matches the repetend, and captures it into backreference number 2.
    • 2+ matches repetitions of the repetend.
    • $ matches end of string.
  • Finally, if the match is null (i.e. there is no match), return null.
  • Otherwise, return an object that contains the repetend (backreference 2) converted to number, and the number of digits between the dot and the repetend (backreference 1).
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement