开发者

javascript eval backslash in window NT path problem

开发者 https://www.devze.com 2023-01-03 07:30 出处:网络
I am experiencing a classic JS case (in my opinion) but after a lot of googling, still not able to find a solution. Backslash is considered as a escape character in JS but what you do when you need to

I am experiencing a classic JS case (in my opinion) but after a lot of googling, still not able to find a solution. Backslash is considered as a escape character in JS but what you do when you need to pass windows path from the JS and print it?

I am using eval because my java applet is executing the code and placing bits when it has a string to evaluate. That's why eval is necessary, however I have made an example which is below:

<div id="mainTabs"></div>
<script>
var s = "document.getElementById('mainTabs').innerHTML='\\C\ganye\file.doc'";
eval(s);
</script>
开发者_如何学运维

I tried double backslashes, not working, if anyone could help me get around this with as less hassle as possible, I will feel grateful.


Because you're using eval, the Javascript interpreter is getting invoked twice - so you need quadruple backslashes, not double:

var s = "document.getElementById('mainTabs').innerHTML='\\\\\\\\C\\\\ganye\\\\file.doc'";

This results in s getting set to:

document.getElementById('mainTabs').innerHTML='\\\\C\\ganye\\file.doc'

so the innerHTML gets set to:

\\C\ganye\file.doc

which is what you wanted. (I'm not sure I understand your reasons for needing eval(), but this is how to work around the problem if you do :-)


You need to quadruple the backslashes, because the the string literal is first interpreted by the JS parser, and then the result is again parsed due to the eval call.

Or, preferably, try to avoid using eval. It is almost never necessary and it adds complication and slows down execution.

This example would work as just: document.getElementById('mainTabs').innerHTML='\\C\ganye\file.doc';

0

精彩评论

暂无评论...
验证码 换一张
取 消