John Louie Dela Cruz
John Louie Dela Cruz

Reputation: 669

Uncaught SyntaxError: Invalid or unexpected token in an inline javascript function with multi line string argument

I have a prepended tr with an inline javascript function with a multi line string argument.

function htmlEncodeMyUnsolved(obj) {
    $('#my-unsolved-reminder-list').prepend(`
        <tr id= "`+ obj.id +`" class ="unsolved-notif" onclick= "viewNote('`+ obj.message +`', `+ obj.id +`)" >\
            <td class ="mailbox-name"><a href="read-mail.html">`+ obj.fromUser +`</a></td>\
            <td class ="mailbox-subject">\
                `+ obj.message +`
            </td>\
            <td class ="mailbox-attachment"></td>\
            <td class ="mailbox-date text-right"> `+ obj.dateAndTime +` </td>\
        </tr>\
    `);
}

this is how it looks in browser inspector:

<tr id="1026" class="unsolved-notif" onclick="viewNote('asd
sdf
sea
qwe')">

And this is the viewNote function:

function viewNote(note) {
    $('p#message').text(note);
}

when i try to click th tr i'm getting an error Uncaught SyntaxError: Invalid or unexpected token, what i'm trying is i want to display multi line text in a p tag. how fix this? thanks in advance.

Upvotes: 0

Views: 2175

Answers (1)

Brett Zamir
Brett Zamir

Reputation: 14355

If you set the following:

obj.message.replace(/\n/g, '\\n')

...it will ensure that the rendered string will escape the new lines (though JavaScript still supplies them to your function as newlines).

Upvotes: 1

Related Questions