-2

while passing string parameters from java to javascript function it breaks if parameters contains space in it.

String str = "This is test";
sb.append("<a href=javascript:testFunction(\""+str+"\";>test</a>");

then while clicking on this hyper link it gives below error as: SyntaxError: unterminated string literal

dfsq
  • 191,768
  • 25
  • 236
  • 258
user3340357
  • 101
  • 1
  • 2
  • 6

2 Answers2

1

You can't use " characters in an HTML attribute value which doesn't have delimiters and you are missing a ).

You could add the missing bits:

sb.append("<a href='javascript:testFunction(\""+str+"\");'>test</a>");

But you would be better off:

  • Not constructing JavaScript by mashing together strings
  • Not constructing HTML by mashing together strings
  • Not using a link to run JavaScript

Such:

var button = document.createElement('button');
button.type = "button";
button.appendChild(
    document.createTextNode('test')
);
button.addEventListener('click', function (event) {
    testFunction(str);
});
ab.append(button); // Assuming that whatever `ab.append` is accepts a DOM element
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You have 2 issues as I see it:

1 - Your href's value isn't wrapped in quotes.

2 - Your function isn't terminated with ).

String strTest = "This is test";
String str = String.Format("<a href=\"javascript:testFunction('{0}');\">test</a>", strTest);
sb.append(str);
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58