问题
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