Search code examples
javascriptregexstringreplacehtml-escape-characters

Replace '\' with '-' in a string


I have seen all the questions asked previously but it didn't help me out . I have a string that contains backslash and i want to replace the backslashes with '-'

var s="adbc\sjhf\fkjfh\af";
s = s.replace(/\\/g,'-');
alert(s);

I thought this is the proper way to do it and of course i am wrong because in alert it shows adbcsjhffkjfhaf but i need it to be like adbc-sjhf-fkjfh-af.

What mistake i do here and what is the reason for it and how to achieve this...??

Working JS Fiddle


Solution

  • Your s is initially adbcsjhffkjfhaf. You meant

    var s="adbc\\sjhf\\fkjfh\\af";