Problem passing kirbytext with line breaks to javascript variable

I’m having a problem getting data from a field and passing it through to a javascript variable. The method I’ve been using up until this point has been working fine, but now I need to get the contents of a textarea field with line breaks, and am unable to do so. The <br /> tags that are inserted cause a syntax error.

Here’s the code I’m using at the end of a template file:

<script type="text/javascript">
<?php foreach($page->imageModules()->toFiles()->shuffle() as $image): ?>
var working = "This text<br />passes through just fine.";
var notWorking = "<?= $image->caption()->kirbytext(); ?>";
<?php endforeach ?>
</script>

And here’s the error it causes:

The <br /> tag from the textarea field breaks the string onto a new line and causes an error, while the <br /> tag from my manually created variable does not.

Can someone help me understand what happens when kirbytext is rendered that causes this?

I would clean the line breaks like that:

<?= Str::replace($image->caption()->kt(), ["\n", "\r"], '') ?>

That works! Thanks for your help.