17

How to remove all backslash in a JavaScript string ?

var str = "one thing\\\'s for certain: power blackouts and surges can damage your equipment.";

I want output like

one thing's for certain: power blackouts and surges can damage your equipment.

Update:

I am scrapping data from page with help of JavaScript & displaying on fancy-box popup.

please help me on this

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
user2046091
  • 369
  • 3
  • 4
  • 12
  • 9
    Just for the sake of future generations: those are **backslash** characters. A slash looks like: `/` – Pointy Apr 23 '13 at 14:00
  • 1
    Does that output come from a database? If so what language are you using there? If so it might be better to remove those backslashes server side – TommyBs Apr 23 '13 at 14:02

4 Answers4

66

Use a simple regex to solve it

str = str.replace(/\\/g, '')

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • it gives output like one thing\\'s for certain: power blackouts and surges can damage your equipment. just removed 1 slash form 3 – user2046091 Apr 23 '13 at 14:02
  • @user2046091: Your example has only one backslash in the string (and two only for escaping in the literal, of whom one is unnecessary)? – Bergi Apr 23 '13 at 14:04
  • 1
    @j08691 it is because there is only one instance of `\ ` in the page, if there are multiple instances then `g` flag is required – Arun P Johny Apr 23 '13 at 14:04
  • @ArunPJohny - doesn't \\ escape the \, meaning it's only looking for a single \? – j08691 Apr 23 '13 at 14:06
  • 4
    As pointed out by @Pointy those are backslashes: to remove **slashes** instead it should be `str = str.replace(/\//g,'')` – caneta May 22 '15 at 14:23
14

This is the answer according to the title as the title is "Remove all slashes in Javascript" not backslashes. So here is the code to remove all the slashes from a string in JavaScript.

str = '/mobiles-phones/.png';
str.replace(/\//g, "")//output would be "mobiles-phones.png";
Safeer Ahmed
  • 587
  • 6
  • 14
3

Regexs are great str.replace(/\\/g,'')

Mike
  • 364
  • 1
  • 9
-3

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

var str = "one thing\\\'s for certain: power blackouts and surges can damage your equipment.";

str.replace("\", "");
Community
  • 1
  • 1
ismail atkurt
  • 139
  • 1
  • 5