0

I have a string like

abcd/123/xyz/345

I want to replace every "/" with "-" using JavaScript. The result string should be abcd-123-xyz-345

I have tried,

string.replace("/","-")

But it replaces the first "/" character only. The result is abcd-123/xyz/345

And

string.replace("///g","-");

is not working as well. Is there any solution for this?

Muhzin
  • 390
  • 6
  • 19

2 Answers2

2

You can use Regex. You need to escape using backslash \ before the /.

A backslash that precedes a special character indicates that the next character is not special and should be interpreted literally

var str = 'abcd/123/xyz/345';
let result = str.replace(/\//g,'-');
console.log(result);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
2

Please try this,

var str='abcd/123/xyz/345'
var newstr=str.split('/').join('-');
console.log(newstr)
JIJOMON K.A
  • 1,290
  • 3
  • 12
  • 29