[javascript] How to globally replace a forward slash in a JavaScript string?

How to globally replace a forward slash in a JavaScript string?

This question is related to javascript

The answer is


Hi a small correction in the above script.. above script skipping the first character when displaying the output.

function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
    if(x.charAt(i) == "/")
    {
        y += "";
    }
    else
    {
        y+= x.charAt(i);
    }
}
return y;   
}

You need to wrap the forward slash to avoid cross browser issues or //commenting out.

str = 'this/that and/if';

var newstr = str.replace(/[/]/g, 'ForwardSlash');

You can create a RegExp object to make it a bit more readable

str.replace(new RegExp('/'), 'foobar');

If you want to replace all of them add the "g" flag

str.replace(new RegExp('/', 'g'), 'foobar');

var str = '/questions'; // input: "/questions"
while(str.indexOf('/') != -1){
   str = str.replace('/', 'http://stackoverflow.com/');
}
alert(str); // output: "http://stackoverflow.com/questions"

The proposed regex /\//g did not work for me; the rest of the line (//g, replacement);) was commented out.


This is Christopher Lincolns idea but with correct code:

function replace(str,find,replace){
    if (find != ""){
        str = str.toString();
        var aStr = str.split(find);
        for(var i = 0; i < aStr.length; i++) {
            if (i > 0){
                str = str + replace + aStr[i];
            }else{
                str = aStr[i];
            }
        }
    }
    return str;
}

Example Usage:

var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');

Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.

Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:

function replace(str,find,replace){
    if (find !== ""){
        str = str.toString().split(find).join(replace);
    }
    return str;
}

This has worked for me in turning "//" into just "/".

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

Without using regex (though I would only do this if the search string is user input):

var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!' 

Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.

var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);

Is this what you want?

'string with / in it'.replace(/\//g, '\\');