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

你。 提交于 2019-12-11 06:33:22

问题


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(/(?<!\\)\./);

回答1:


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.



来源:https://stackoverflow.com/questions/13320767/javascript-regexp-that-matches-not-preceded-by-lookbehind-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!