kolinunlt
kolinunlt

Reputation: 345

Javascript - Use string concat, spaces cause errors

The following is a code snippet

var str1 = "test"
var str2 = "cdfeeef f33sdeeee";
document.write("<td>" + str1 + "</td>");
document.write("<td><a href=('"+str1+"','"+str2+"')>TEST</td>");

I tried to make a table and write some parameters

But as long as the parameter has spaces, it will be wrong

I went through the console and found that the result is

<a href="('test','cdfeeef" f33sdeeee')="">TEST</a>

str2 be cut, str2 has double quotes

How can I adjust, can the following results appear?

<a href="('test','cdfeeef f33sdeeee')="">TEST</a>

Upvotes: 1

Views: 116

Answers (2)

nayi224
nayi224

Reputation: 565

spaces will not cause an error, you just put the " or ' in the wrong place.

document.write("<td><a href=\"('"+str1+"','"+str2+"')=\"\">TEST</td>");
//<a href="('test','cdfeeef f33sdeeee')=" ">Test

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370689

A nicer approach would be to avoid document.write completely and assign to the href of the element instead of writing HTML markup. Something like:

// this approach will also reduce XSS vulnerabilities
tr.appendChild(document.createElement('td')).textContent = str1;
const td2 = tr.appendChild(document.createElement('td'));
const a = td2.appendChild(document.createElement('a'));
a.textContent = 'TEST';
a.href = `('${str1}','${str2}')=`;

I'm not entirely sure what the stuff inside the href is supposed to be, though - in your real code, is that a function call? If so, an even better approach would be:

// this approach will eliminate XSS vulnerabilities
tr.appendChild(document.createElement('td')).textContent = str1;
const td2 = tr.appendChild(document.createElement('td'));
const a = td2.appendChild(document.createElement('a'));
a.textContent = 'TEST';
a.addEventListener('click', () => {
    someFn(str1, str2);
});

so there aren't any escaping issues at all.

Upvotes: 3

Related Questions