1

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?

2 Answers 2

1

It is because apostrophe needs to be escaped. you can escape it through &apos; .

check here for all valid formats

You can replace occurrences of apostrophe in the controller, with

some_string_param.replaceAll("'", "&apos;");

before you set them in the request.

Read How to escape special characters in jsp

Sign up to request clarification or add additional context in comments.

8 Comments

should be a html encoding function somewhere that OP can use, instead of manually doing it like this
do you mean I should rearrange the value of my some_string_param value? I mean, I should parse this value and replcae all apostrophes in it?
@Karthik T Can you show me how to inject jst c:out features into my function invokation? I would be very pleased)
@nightin_gale What I was suggesting was to use HtmlUtils.htmlEscape to escape the string before using it as in your question
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.