How to globally replace a forward slash in a JavaScript string?
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);
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;
}
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');
This has worked for me in turning "//"
into just "/"
.
str.replace(/\/\//g, '/');
Is this what you want?
'string with / in it'.replace(/\//g, '\\');
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');