开发者

Escape char problem while generating JavaScript page through Java code?

开发者 https://www.devze.com 2022-12-10 13:03 出处:网络
I am generating JavaScript pages through Java code like: FileOutputStream fs=new FileOutputStream(\"C:\\\\Documents and Settings\\\\prajakta\\\\Desktop\\\\searcheng.html\");

I am generating JavaScript pages through Java code like:

FileOutputStream fs=new FileOutputStream("C:\\Documents and Settings\\prajakta\\Desktop\\searcheng.html");
OutputStreamWriter out=new OutputStreamWriter(fs);
out.write("<script language='JavaScript' type='text/javascript'>");
out.write("var str=new String('C:\\Documents and  Settings\\prajakta\\Desktop\\substr.html');");
out.write("var beg=str.lastIndexOf('\\');");//double' \' **Problem Stmt**

And so on.

The problem is when searcheng.html is created it contains

var beg=str.lastIndexOf('\');//single '/'

which creates a problem in finding index of '\'. How should I write this problem so that it will contain double "\"?

Similarly how should I write a statement

out.write("document.write('< 开发者_如何学Pythona href='str'> '+str.slice(beg+1,end)+' </a>');"); 

so that it will create statement in JavaScript as

document.write('< a href=" 'str' ">  '+str.slice(beg+1,end)+'  </a>');

and the link will go to page whose address is stored in str?


out.write("var beg=str.lastIndexOf('\\\\');");

should do the trick. Double for Java, double again for JavaScript...


In Java string literals the backslash character has a special meaning as a escape character. If you want to represent the backslash character itself you will need to escape it with itself.

That's why the Java String literal "\\" represents a String with one letter, that letter being a backslash.

If you want to represent a String with two backslashes you will need to escape both in your literal: "\\\\".


Try this:

    out.write("var beg=str.lastIndexOf('\\\\\\');");

The point is that '\' is the escape character in Java, so to have 1, you must write 2. To have 2, you must write 4.

0

精彩评论

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