How to remove slash from a string in JavaScript

1

I get a text with JavaScript and sent it by ajax, but I want to remove all the slash that the string can bring as such and replace it with "-"

Text that captures in the information variable: Send data to CE / SE to the person in charge /// Juan or to the person in charge //// pedro

var str = información;
var res = str.replace("/", "-");
alert(res);

With the previous method it would show this: Send data to CE-SE to the person in charge /// Juan or to the person in charge //// pedro

It only works when there is a clear slash, in the method I asked for that, but I could not do a method to remove all the slash and replace it with "-" if I import the amount of slash, that is my problem and it would be very repetitive to do this

var str = información;
var res = str.replace("///", "-");
alert(res);

var str = información;
var res = str.replace("/", "-");
alert(res);

var str = información;
var res = str.replace("////", "-");
alert(res);

Sensing the amount, I do not want to do that if not a method that can do everything regardless of the amount of slash and change them by "-"

    
asked by R3d3r 82 21.11.2018 в 15:22
source

2 answers

6

You could do the replace in this way:

var str = "abc/def/ghi/jkm/.../..n";
var res = str.replace(/\//g, "-");
console.log(res);

In the first parameter of the replace is a regular expression, you declare it with two bar // , inside those two bars you place the expression that will contain the rules, in your case you need to replace the bar with a hyphen, but since the bar (/) would affect the expression then you prepend a backslash to indicate that it is an escape character. the g at the end indicates that you want to apply it globally.

You can also try to use the new RegExp("/", "g"); more information here .

    
answered by 21.11.2018 в 15:45
1

The string replace method supports regular expressions in MDN you can investigate further if you get a string in this format '//// Pedro // Carlos / Juan' you will have to replace the characters '/' in a global way, besides if there are consecutively '///' with the expression "+" you will be requiring that also I took it out as a group of characters. You have to be especially careful because '/' must be escaped with an inverted slash \ leaving it like this:

const str = '////Pedro//Carlos/Juan';

const res = str.replace(/\/+/g,'-');

console.log(res);
    
answered by 21.11.2018 в 15:59