How to Remove Forward and Backward Slashes from String in JavaScript

How to remove forward and backward slashes from string in javascript

You can just replace \/ or (|) \\ to remove all occurrences:

var str = "//hcandna\\"console.log( str.replace(/\\|\//g,'') );

Remove all backslashes in Javascript

Use a simple regex to solve it

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

Demo: Fiddle

Replace back slash (\) with forward slash (/)

You have to escape to backslashes.

var path = "C:\\test1\\test2";var path2 = path.replace(/\\/g, "/");console.log(path2);

How to replace backward slash with forward in js

Your regex is fine but variable declaration needs double backslash because single backslash is interpreted as escape character:

var path = 'C:\\Users\\abc\\AppData\\Local\\Programs\\Python\\Python37\\python.exe';path = path.replace(/\\/g, "/");
console.log(path);//=> C:/Users/abc/AppData/Local/Programs/Python/Python37/python.exe

Replace forward slash "/ " character in JavaScript string?

You need to escape your slash.

/\//g

how to replace the forward slash to backslash and forward slash using javascript

use replace:

"http:/www.freeformatter.com/javascript-escape.html".replace(/\//g, "\\/");

If you have the string in a variable:

var url = "http:/www.freeformatter.com/javascript-escape.html";
url.replace(/\//g, "\\/");

replace backslashes with forward slashes regex in javascript

Use the regex pattern without a string type

path.replace(/\\/g, "/")

Replace Backward Slashes with Forward Slashes Javascript

This is not possible — with the provided example-string or anything similar.

\x is the first problem here. JavaScript thinks this is a Hexadecimal escape sequence, that's why the JavaScript-Interpreter is throwing an appropriate error:

Uncaught SyntaxError: Invalid hexadecimal escape sequence

And even if we take another example string: 'http:\\www.xyz.com\yy\ab\1324\1324.jpg' it will fail.

JavaScript thinks that the backslashes are there to escape something as Octal escape sequence — that is why just entering this string into a JS-Console and hitting return gives you back:

"http:\www.xyz.comyyabZ4Z4.jpg"

To visualize it even more, enter into your console: 'http:\\www.xyz.com\yy\ab\1324\1324.jpg'.split('');

You'll see that even \132 gets converted to Z.

I tried many things right now, like replacing/escaping, trying JSON.stringify, using a text-node, using CDATA inside a virtual XML-document, etc. etc. – nothing worked. If somebody finds a JavaScript-way for doing this, I'd be happy to know about it!


Conclusion

I don't know of any way for doing this inside JavaScript. There seems to be no chance.

Your only solution as I see it, is to escape it on the server-side.

In your case you will have to write a little server-script, that calls your used API and converts/escapes everything to be ready for your JS. And your JS calls this little server-script.



Related Topics



Leave a reply



Submit