replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.
When showing alternatives, use 'or' instead of a forward slash.
You need to escape the / with a \ . Show activity on this post. You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex. See example in JSFiddle.
A slash. A slash symbol '/' is not a special character, but in JavaScript it is used to open and close the regexp: /... pattern.../ , so we should escape it too.
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');
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);
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!'
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');
Is this what you want?
'string with / in it'.replace(/\//g, '\\');
This has worked for me in turning "//"
into just "/"
.
str.replace(/\/\//g, '/');
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With