如何在 Rails 中格式化这个国际电话号码?
问题描述:
如果我有这样的国际电话号码:
If I have an international phone number such as this:
0541754301
我如何格式化它以产生这样的东西:
how can I format it to produce something like this:
0541-754-301
0541-754-301
答
您可以使用 ActionView::Helpers::NumberHelper
但是,文档指出此方法将数字格式化为美国电话号码(例如 (555) 123-9876).
However, the docs point out that this method formats a number into a US phone number (e.g., (555) 123-9876).
相反,您可以使用 这个补丁,它增加了提供数字分组的能力:
Instead you could use this patch which adds the ability to provide number groupings:
:groupings - Specifies alternate groupings
(must specify 3-element array; defaults to [3, 3, 4])
所以在你的情况下你会打电话:
So in your case you would call:
number_to_phone('0541754301', :groupings => [4, 3, 3], :delimiter => "-")
生产:
0541-754-301
0541-754-301