Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all backslashes in a string with a pipe

Tags:

I have the string: \rnosapmdwq\salesforce\R3Q\OutputFiles\Archive

I'm getting a unrecognized escape sequence when I try to send this to a .NET web service.

I'm trying to replace all of the "\" with "|" to send it to the server.

I know I can use the replace method but that only replaces the first element. I think I need to use a regular expression to solve it.

Here's what I have so far:

Path = Path.replace("\\/g", "|"); 

This is wrong though.

like image 278
Nate Avatar asked Aug 10 '11 17:08

Nate


People also ask

How do you replace a backslash on a string?

To replace all backslashes in a string:Call the replaceAll() method, passing it a string containing two backslashes as the first parameter and the replacement string as the second. The replaceAll method will return a new string with all backslashes replaced by the provided replacement.

How do you replace all the in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.


2 Answers

You don't need to make a regex a string, and it helps having that first / in there

Path = Path.replace(/\\/g, "|") 
like image 128
Griffin Avatar answered Sep 20 '22 02:09

Griffin


The correct syntax would be: Path = Path.replace(/\\/g, "|");

Working example at: http://jsfiddle.net/eDKej/.

Example (extra code for demonstration purposes only):

var Path = $("#path").text(); Path  = Path.replace(/\\/g, "|"); $("#new-path").append(Path); 
like image 29
Robert Avatar answered Sep 20 '22 02:09

Robert