174

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

0

11 Answers 11

323

The following would do but only will replace one occurence:

"string".replace('/', 'ForwardSlash');

For a global replacement, or if you prefer regular expressions, you just have to escape the slash:

"string".replace(/\//g, 'ForwardSlash');
Sign up to request clarification or add additional context in comments.

11 Comments

First snippet does not do global replacement. Not too sure how to do global replacement the non-regex way.
Ah right, I didn't try it with more than a slash. It could be done with "string".replace('/', 'ForwardSlash', 'g') but that is non-standard argument that works only in Firefox afaik.
"string".replace(/\//g, 'ForwardSlash'); works but remove the /g from this and it doesn't work.
@johntrepreneur the g indicates it's a global replacement, i.e. it replaces all instances of the matched /. Without the g it only replaces one instance. And if you remove /g you break the regex completely since the last / is the end-delimiter.
@RameshRajendran that's just the way the API is.. by default it replaces only once then stops when it found one to replace. See also developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
|
34

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);

Comments

13

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');

Comments

8

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!' 

Comments

5

Is this what you want?

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

Comments

5

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

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

Comments

1

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;   
}

Comments

1

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;
}

Comments

0
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.

2 Comments

Please note that I'm not certain how performance of this compares the proposed array split/join solution.
... stumbled over this ... try different IDE using smarter syntax highlighting. Don't rely on colors of your code editor, but believe in power of stateful parsers properly tokenizing your code at runtime.
0

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');

Comments

0

An alternative to '/'.replace(/\//g, 'Replaced') could be

'/'.split('/').join('Replaced')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.