简体   繁体   中英

escape & unescape backslashes using Javascript/jQuery

Here are the test cases

  • \\\\192.168.100.1\\foldername\\filename
  • actividirectoryName\\username
  • somethingelse\\text\\\\and this
  • \\

How do I escape these strings and again un-escape it.

I tried something like this "mystring\\something".replace(/[\\\\]/g, '\\\\\\\\'); but it do sent work right when I have string like "name\\b" or "text\\n" or "text\\t"

Since those are reserved keys to tab, newline and other. What is the best way to handle this

Update: even here in this edit i had to write 3 back slashes to show you two back slashes? when I first wrote 2 back slashes, it was showing only 1 back slash

Depending on how you want to solve this depends on where these strings are stored.

There are only two ways of handling this, both of which require storing the variables else where before using them.

If you are using php you can use Raw. If you are doing ajax requests or loading values into the DOM, you can use javascript to get those values, and they will be held with the baskslashes.

 var text = document.getElementById('id'); var a = document.getElementById('v').value; var b = String.raw `${a}` var c = String.raw `\\\\192.168.100.1\\foldername\\filename` var d = '\\\\192.168.100.1\\foldername\\filename' var test = [ d + ' - in JavaScript', c + ' - in raw', a + ' - in HTML', b + ' - in raw variable' ]; for (var i = 0, l = test.length; i < l; i++) { text.value += test[i] + '\\n'; } 
 textarea { width: 100%; } 
 <input id='v' value='\\\\192.168.100.1\\foldername\\filename' type='hidden' /> <textarea rows='10' id='id'></textarea> 

To use php and raw it would look something like this

String.raw`<?=$variable?>`

EDIT Once you have this raw data you can start using REGEX and other escaping means on it.

 var c = String.raw `\\\\192.168.100.1\\foldername\\filename<\\/p>` var text2 = document.getElementById('id2'); text2.value = (c + '').replace('\\\\\\\\', '\\\\').replace('\\\\/', '/'); 
 textarea { width: 100%; } 
 <textarea rows='10' id='id2'></textarea> 

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