1

I have an array of objects which are phone numbers such as:

phoneArray = [{"phone": "+11 111 111"},{"phone": "+22 222 222"}]

I did a loop on it to remove spaces because I want this result:

[{"phone": "+11111111"},{"phone": "+22222222"}]

but I only could remove the first space which looked like

[{"phone": "+11111 111"},{"phone": "+22222 222"}

with this code:

for(i=0 ; i<phoneArray.length ; i++) {

let test = phoneArray[i].phone.replace(" ","");
}

I actually have other phone numbers like {"phone": "(22) 222-222"} to format but if I can remove space I can remove other signes like ()- I think.

I don't use regex because I don't understand it yet.

Gron465
  • 25
  • 1
  • 9
  • 2
    you need to use the regex to replace all spaces: `.replace(/ /g,"")` – Lux Jan 26 '22 at 14:19
  • Turn it the other way around: you want to remove everything *but* numbers and "+"… – deceze Jan 26 '22 at 14:20
  • 1
    Does this answer your question? [How to replace all occurrences of a string in JavaScript](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Lux Jan 26 '22 at 14:20
  • 1
    Does this answer your question? [replace nonNumeric characters with javascript?](https://stackoverflow.com/questions/6097305/replace-nonnumeric-characters-with-javascript) – Raul Sauco Jan 26 '22 at 14:21

4 Answers4

3

To remove all characters except for + and numbers, you can do this:

let p = "+1 (555) 555-555"

console.log(p.replace(/[^\d\+]/g,''))
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
2

You can pass a regex pattern to your replace function. Like that:

let p = "+(11) 111 111-11"

console.log(p.replace(/[\s\-\(\)]/g,''))
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
1

I would use the map function to iterate the array and change each of the values, to each value will apply the function replace with a regex in order to remove the non digits number and +.

phoneArray = [{"phone": "+11 111 111"},{"phone": "+22 222 222"}]
phoneArray = phoneArray.map(p => {
   return {
     phone: p.phone.replace(/[^+\d+]/g,"")
   }
})
console.log(phoneArray)
-2

You can try phone.replace(/\D/g,'') this will replace all non-numeric characters and will give you the numbers, hope this helps.enter image description here