Search code examples
javascriptregexlookbehind

Javascript regexp that matches '.' not preceded by '\' (lookbehind alternative)


I am making a (Excel like) number formater function in javascript. I want to use templates like "0 000.00" and "000.000.000" which would produce:

format(123456789,"0 000.00") >> "123 456 789.00"
format(123456789,"000\.000\.000") >> "123.456.789"

So I need to match '.' not preceded by '\'. Since there is no lookbehind in javascript, what would be the regexp for splitting the whole and decimal part of a template?

This unfortunately doesn't work :-(

template.split(/(?<!\\)\./);

Solution

  • Reverse the string and use a negative lookahead instead.

    template.split("").reverse().join("")
            .split(/\.(?!\\)/)
            .split("").reverse().join("");
    

    That's a "fun" way of doing it but for your case there are other ways that may be better. Like replacing all \. with a magic string like __MAGIC__, splitting by ., then undoing the magic strings.