How to strip off leading 1 from a phone number

I am trying to strip off leading 1 from a phone number in my rails app. Currently I have a params called faxnumber to equal a regular expression but i need the 1 to be stripped off

params[:faxnumber] =~ /^1\d{3}-\d{3}-\d{4}$/
1732-555-7777 i want it to be 732-555-7777

params[:faxnumber] =~ /^1\d{3}\d{3}\d{4}$/
17325557777 i want it to be 7325557777

How about something like this?

"1g4143".split('').drop(1).join('') if "1g4143"[0] == '1'

or this?


i got it to work with using this
params[:faxnumber].sub!(/^1/, “”)
this will remove the leading 1 from both instances for what I want

but the only thing now is that when i enter a number that is not supposed to work I get an error message saying

undefined method `sub!’ for nil:NilClass

not sure why I am getting that.

Well the error message says you are trying to apply the method sub!, to a NilClass.

I found a work around to that issue. but my regular expression needs some work.
right now i only need to accept numbers from the following
011 any number or amount after that is fine
this is my regular expression which is matching everything right now that i need but it is also matching more than 10 digits for numbers such as 732333444456959 it matches part of it but i need it to match none. any help would be appreciated

Not sure about rails, but in Ruby:

n, prefix = '1111123458', ?1                            # => ["1111123458", "1"]
n.delete_prefix!(prefix) while n.start_with?(prefix)    # => nil
p n                                                     # => "23458"

Loops because using unnecessary Regexp can lead to more CPU and memory usage (for example, Avoiding regexp in avoidable situations can be a good idea…

You can run regexp after the strip, which makes the computation easier for your system.

I used this method. It is effective but sophisticated.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs