Search code examples
javascriptunicodecarriage-returnunicode-escapes

What is the JavaScript Escape code for Unicode Carriage Return?


If I ever need to include a newline in a HTML title attribute tooltip, I use the HTML Escape Character for Carriage Return:

  • 

Example:

  • <img src="" title="Line 1&#013;Line 2" alt="" />

Apparently, &#13; also works, so I'm unclear where I learned to include the leading zero.


However, inserting &#013; doesn't work when dynamically creating an HTML element in JavaScript.

Working Example:

Hover over the examples below to see the difference in how the tooltips are displayed.

const myImage = document.createElement('img');
myImage.setAttribute('src', '');
myImage.setAttribute('width', '100');
myImage.setAttribute('height', '100');
myImage.setAttribute('title', 'test line 1&#13;&#13;test line 2');
myImage.setAttribute('alt', '');
document.body.appendChild(myImage);
<img src="" width="100" height="100" title="test line 1&#013;&#013;test line 2" alt="" />


Question:

What JavaScript Escape should I use instead of the HTML Escape &#013; ?

N.B. Yes, I know I can use \n - but in JavaScript that represents a newline literal.

In this case I simply want to include in my string the JavaScript Escape for ASCII / Unicode Carriage Return - basically, the JavaScript equivalent of &#013; in HTML.


Solution

  • Got it. Thanks, everyone.

    The answer I was looking for is:

    • \u000D is the JavaScript Escape equivalent of the HTML Escape &#013;

    Working Example:

    const myImage = document.createElement('img');
    myImage.setAttribute('src', '');
    myImage.setAttribute('width', '100');
    myImage.setAttribute('height', '100');
    myImage.setAttribute('title', 'test line 1\u000D\u000Dtest line 2');
    myImage.setAttribute('alt', '');
    document.body.appendChild(myImage);
    <img src="" width="100" height="100" title="test line 1&#013;&#013;test line 2" alt="" />