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?

"1g4143".sub(/^[1]/,'')

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
732-222-3333
7325551111
1732-256-2312
17329905049
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
(?:^011\d*)?(?:^1)?\d{3}(?:-)?\d{3}(?:-)?\d{4}$

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, https://stackoverflow.com/a/3614592/11089758). 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.

Sponsor our Newsletter | Privacy Policy | Terms of Service