1

I have a string like (which is a shared path)

\\cnyc12p20005c\mkt$\\XYZ\

I need to replace all \\ with single slash so that I can display it in textbox. Since it's a shared path the starting \\ should not be removed. All others can be removed.

How can I achieve this in JavaScript?

0

2 Answers 2

4

You could do it like this:

var newStr = str.replace(/(.)\\{2}/, "$1\\");

Or this, if you don't like having boobs in your code:

var newStr = "\\" + str.split(/\\{1,2}/).join("\\");
Sign up to request clarification or add additional context in comments.

Comments

0

You can use regular expression to achieve this:

var s = '\\\\cnyc12p20005c\\mkt$\\\\XYZ\\';
console.log(s.replace(/.\\\\/g, '\\')); //will output \\cnyc12p20005c\mkt$\XYZ\

Double backslashes are used because backslash is special character and need to be escaped.

2 Comments

s.replace(/.\\/g, '/') gives \\\cnyc12p20005c\mkt$\\XYZ\
not /.\\/g, but /.\\\\/g. It was answer for your unedited question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.