简体   繁体   English

使用Javascript / jQuery转义和转义反斜线

[英]escape & unescape backslashes using Javascript/jQuery

Here are the test cases 这是测试用例

  • \\\\192.168.100.1\\foldername\\filename \\\\ 192.168.100.1 \\文件夹\\文件名
  • actividirectoryName\\username actividirectoryName \\用户名
  • somethingelse\\text\\\\and this someelse \\ text \\\\和这个
  • \\ \\

How do I escape these strings and again un-escape it. 如何转义这些字符串,然后再次转义。

I tried something like this "mystring\\something".replace(/[\\\\]/g, '\\\\\\\\'); 我尝试了类似"mystring\\something".replace(/[\\\\]/g, '\\\\\\\\'); but it do sent work right when I have string like "name\\b" or "text\\n" or "text\\t" 但是当我有"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? 更新:即使在此编辑中,我也必须写3个反斜杠才能向您显示两个反斜杠? when I first wrote 2 back slashes, it was showing only 1 back slash 当我第一次写2个反斜杠时,它只显示1个反斜杠

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. 如果您使用的是php,则可以使用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. 如果您正在执行ajax请求或将值加载到DOM中,则可以使用javascript获取这些值,并且这些值将以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 要使用php和raw,它将看起来像这样

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

EDIT Once you have this raw data you can start using REGEX and other escaping means on it. 编辑一旦有了这些原始数据,就可以开始使用REGEX和其他转义手段。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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