2

I think what i'm trying to do is possible... but I haven't found an answer that achieves that yet. I would like to format a string which will be similar to this in javascript:

+44 (0) 234-567-8901

The proceeding international ( +44 ) and local ( (0) ) calling code are subject to change, so the string could be longer or shorter. However the format is always the same.

I would like to take this string and remove all characters including whitespaces up to the second whitespace and remove dashes. e.g:

+44 (0) 234-567-8901 becomes 2345678901

Can anyone help?

Thanks

  • [What have you tried?](http://whathaveyoutried.com) – JaredMcAteer Jul 18 '12 at 15:03
  • 1
    Have a look at `indexOf` (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf) and http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – Felix Kling Jul 18 '12 at 15:03
  • This is the closest i've got `^[^\)]+(?=\))` which using the example above returns `+4402345678901` – user1535196 Jul 18 '12 at 15:09

2 Answers2

2

Going by your own requirements (remove everything up to and including the second whitespace, and remove dashes from the remaining);

Use this pattern ^([\S]+\s){2}|- and replace with nothing. You should be left with a number similar to what you asked for (+44 (0) 234-567-8901 becomes 2345678901).

Thorbear
  • 2,303
  • 28
  • 23
1

If you can rely on the ending format of the string to be a consistent number of characters, you can grab the last 12 characters, and remove the dashes.

var result = str.slice(-12).replace(/-/g, "");

If you really just want a regex, you can do this...

var result = str.match(/(\d{3})-(\d{3})-(\d{4})$/).slice(1).join("");

Again, this relies on consistency of the end of the string. If there may be variation, you'll need to adjust to compensate.


To get everything after the last whitespace, change the slice() in the first example to this...

.slice(str.lastIndexOf(' ') + 1)

To get everything after the second whitespace, change the slice() to this...

.slice(str.indexOf(' ', str.indexOf(' ') + 1) + 1)
  • For most cases I could rely on the last 12 characters as these will be UK numbers, however there will be some international numbers so its not a complete solution unfortunately. Is there no way to search by whitespace number and delete everything before? – user1535196 Jul 18 '12 at 15:23
  • @user1535196: If you want everything after the *last* whitespace, do this... `str.slice(str.lastIndexOf(' ') + 1)` –  Jul 18 '12 at 15:25