简体   繁体   中英

How can I display special chars in an alert box using javascript?

I want to display special chars as an alert box using javascript and jsp...

String encodeString = "ss\ncc";
String test = "DisplayNext('"+encodeString+"')";
String NextLink = "<br><a href='#' onclick="+test+"> Next</a>";

That is

function DisplayNext(Next){
   alert(Next);
}

Though I've used special chars I am not able to display them in an alert box. How can I sort this out?

Your code produce something like this:

<br><a href='#' onclick="DisplayNext('ss
cc');"> Next</a>

And what you need is:

<br><a href='#' onclick="DisplayNext('ss\ncc');"> Next</a>

If you want a line break in javascript it must look as \\\\n in java. So use:

String encodeString = "ss\\ncc";
String test = "DisplayNext('"+encodeString+"')";
String NextLink = "<br><a href='#' onclick="+test+"> Next</a>";

Also consider using a special function to escape your String objects as javascript values. Google will easily help you find it ;)

If your String is URLEncoded in java you need to unescape it in javascript.

Java:

    String s = "ë";
    System.out.println(URLEncoder.encode(s, "ISO-8859-1"));

this will print out %EB

Javascript:

alert(unescape('%EB'));

this will print out the character ë in alert message

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