1

The goal

99999999 to 9999 9999.

The problem

I searched for String.split, but I couldn't apply. I don't want to separate the string into two variables, I just want to separate the string to displaying proposals.

The scenario

There is the following fragment on my application:

var contactPhone = "91929394";

And I want to separate 91929394 into 9192 9394 by calling the same variable (contactPhone).

Clarifying know-how questions

I really don't know the syntax, even not how I have to search for. Take it easy — it is a programming question.

8
  • That should be a string, not a number. Commented Aug 29, 2013 at 13:51
  • That's a number, not a string. How are you displaying it? Commented Aug 29, 2013 at 13:51
  • Do you always want to split into blocks of 4 digits? Commented Aug 29, 2013 at 13:52
  • Guys, my bad. I already changed for integer. And @MatthewRiches, I don't understand your question. Commented Aug 29, 2013 at 13:54
  • 2
    @GuilhermeOderdenge: Phone numbers are not integers. If you can't add it, it isn't a number. You should only use strings. Commented Aug 29, 2013 at 13:55

5 Answers 5

4

Use contactPhone.replace(/(\d{4})(\d{4})/, '$1 $2')

It will split the phone number into two groups, with 4 digits each.

If contactPhone is a number and not a string, you can use contactPhone.toString() before using the regex replace.

Sign up to request clarification or add additional context in comments.

1 Comment

Hello, @dcro. Your answer is concisely and clear — thank you! And about the confusion about the type of my variable, don't worry because was my mistake. I've expressed myself badly.
3

You could simply;

var formatted = contactPhone.toString();
formatted = formatted.substr(0, 4) + " " + formatted.substr(4);

Comments

0

try this:

function sep(str){
    var len = str.length;
    var a = len/2;
    return str.substring(0, a) + ' ' + str.substring(a, len);
}

Comments

0

If you wanted to be more robust, you could add a space after every 4th character?

contactPhone.replace(/.{1,4}/g, '$& ');

Comments

-1

Does this help?

function splitInTwo(s){
    return [s.substring(0, s.length/2), s.substring(s.length/2)]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.