简体   繁体   中英

Replace Characters from string with javascript

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?

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("\\");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM