0

I have string like 888-888-8888.

I want to remove all '-' from string.

How can i achieve this ? i tried below but it removes only first - .

var phone = '888-888-8888';
phone = phone.replace('-', '');
alert(phone);
str
  • 38,402
  • 15
  • 99
  • 123

4 Answers4

3

Use .replace with a globaly flagged Regular Expression:

var phone = '888-888-8888';
phone = phone.replace(/\-/g, '');
alert(phone);
Koby Douek
  • 15,427
  • 16
  • 64
  • 91
1

You need to use the replace() function for replacing the character occurrence from the string

var phone = '888-888-8888';
phone = phone.replace(/\-/g, '');
alert(phone);

Note that: The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. So we use /g for global search and replace.

 var phone = '888-888-8888';
phone = phone.replace(/\-/g, '');
alert(phone);
Koby Douek
  • 15,427
  • 16
  • 64
  • 91
Ankit Agarwal
  • 29,658
  • 5
  • 35
  • 59
0

Please check it,

var phone = '888-888-8888';
var newphone = phone.replace(/-/g, "");
alert(newphone);
Gajjar Chintan
  • 392
  • 2
  • 8
0

you need to include the Global Flag

var phone = "888-888-8888";
var newPhone = phone.replace(/-/g, "");

https://codepen.io/anon/pen/LjaBjq