I'm running into a problem where, I'm assigning a Laravel variable (in blade) to a JS variable, but the Laravel variable has multiple double and single quotes, backticks and unescaped endlines in it.
If I use a PHP function such as addslashes, JS gives me the following error:
Uncaught SyntaxError: "" string literal contains an unescaped line break
Is there any Laravel helper or something that can escape the backticks in the string? or is there any helper that can escape my unescaped line breaks? I could use that injunction with addslashes.
My Laravel Code:
web.php
Route::get("/{user:username}/{note:share_token}", [HomeController::class, "share"])->name("note.share.index")->withoutMiddleware(["auth"]);
HomeController.php
public function share(User $user, Note $note)
{
if ($user->username === $note->user->username)
{
$note->body = addslashes($note->body);
return view("share", ["user" => $user, "note" => $note]);
}
abort(404);
}
Javascript
let body = "{{ $note->body }}";
Basically my laravel variable is the value of monaco editor in database and I want to set the value of monaco editor from JS so I can't directly place the variable in html. If I am to use fetch/ajax, I can properly deal with this, but I don't want to use that, it will be a waste of resources and time.
I've figured a solution for the time being
I escape backticks (`) and linebreaks (\n) in this so that it can be handled in JS
HomeController.php
public function share(User $user, Note $note)
{
if ($user->username === $note->user->username)
{
$note->body = str_replace('`', '\`', $note->body);
$note->body = str_replace(array("\r\n", "\n", "\r"), '\\n', $note->body);
// dd($note->body);
return view("share", ["user" => $user, "note" => $note]);
}
abort(404);
}
And I used {!! $note->body !!} so that it does not escape html characters.
JavaScript
let body = `{!! $note->body !!}`;
My markdown parser will automatically escape the characters that need it. I did this because, all of the html characters and double quotes and angle brackets were being escaped, and since they were already escaped, the markdown parser was not parsing them. I'm using Remarkable and it does not parse html (escapes it), just markdown. So it is relatively safe I suppose.