简体   繁体   中英

Safely pass strings from Java .properties file to a string processed by JavaScript

I've run into a problem with internationalization and need to know the best way to move forward. we use java ResourceBundle with .properties files to internationalize the content on our software. There are areas where a dynamic value gets passed to a JavaScript alert, for example

#.properties file with ca_ES locale
warningText=regles d’apostrofació

#JavaScript with the property as parameter
<script>
    alert('warningText');
</script>

So the apostrophe in the value for warningText escapes the string and causes a fatal error. We can't really use double quotes instead because of our coding standards, and it would be a ton of work to go through and change all of the code to double quotes, and we can't use something like &quot; because html tags don't resolve inside a javascript alert.

Lastly if within the string in the properties file we did something like this:

warningText=regles d\’apostrofació

the escape is applied during compilation or in the JVM or somewhere prior to the javascript and we end up just escaping the string anyways

You may simply use unicodes \\uxxxx instead of unicode characters into properties file which are also supported by browsers, below are the unicodes for regles d'apostrofació :

#warningText=regles d’apostrofació
warningText=\u0072\u0065\u0067\u006c\u0065\u0073\u0020\u0064\u2019\u0061\u0070\u006f\u0073\u0074\u0072\u006f\u0066\u0061\u0063\u0069\u00f3

 alert('\r\e\g\l\e\s\ \d\’\a\p\o\s\t\r\o\f\a\c\i\ó') 

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