Reputation: 831
I run into one small problem.
<button onclick="foo('${some_string_param}')"></button>
It goes without any trouble when some_string_param
doesn't contain apostrophe. But when it contains any apostrophe, it goes with Uncaught SyntaxError: Unexpected identifier error.
What should I change in my foo invocation?
Upvotes: 1
Views: 1269
Reputation: 31962
Figured Ill write the answer instead of a long comment chain. As @SanKrish said, you need to escape characters which have significance in your code, or in html, before you can put it there. To prevent issues like you are having. The apostrophe is just one of the characters.
The cleaner way is to use HtmlUtils.htmlEscape
to escape your string before using it.
Either
<button onclick="foo('${HtmlUtils.htmlEscape(some_string_param)}')"></button>
or
//Somewhere
some_string_param = HtmlUtils.htmlEscape(some_string_param);
//later in the view
<button onclick="foo('${some_string_param}')"></button>
I suggest the first way cuz its more obvious, but I am not sure its right syntax, cuz I dont know JSP
Edit: Seems HtmlUtils
is from spring. If you arent using it, StringEscapeUtils
is another alternative from apache commons.
Copied from the linked article
1) StringEscapeUtils from Apache's commons lang library.
2) HtmlUtils from Spring
3) Own custom method using String replace
Upvotes: 0
Reputation: 8207
It is because apostrophe
needs to be escaped. you can escape it through '
.
check here for all valid formats
You can replace occurrences of apostrophe in the controller, with
some_string_param.replaceAll("'", "'");
before you set them in the request.
Read How to escape special characters in jsp
Upvotes: 1