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
  • 42,689
  • 17
  • 109
  • 127

4 Answers4

3

Use .replace with a globaly flagged Regular Expression:

var phone = '888-888-8888';
phone = phone.replace(/\-/g, '');
alert(phone);
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
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
  • 16,156
  • 19
  • 74
  • 103
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Please check it,

var phone = '888-888-8888';
var newphone = phone.replace(/-/g, "");
alert(newphone);
Gajjar Chintan
  • 420
  • 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