For example:
var str="abc\'defgh\'123";
I want to remove all the \
using Javascript. I have tried with several functions but still can't replace all the forward slashes.
For example:
var str="abc\'defgh\'123";
I want to remove all the \
using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As @Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join()
approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \
with another \
. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str
, will work with the original string, without the replacements.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\'
in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"