-1

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.

Rounin
  • 27,134
  • 9
  • 83
  • 108
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences — `\r` or `\x0D` should do… – deceze Sep 09 '22 at 10:11
  • 2
    @Ouroborus No, a newline is different from a carriage return. Not sure it really makes a difference in OP's case; it may or it mayn't, reserving judgement on that… – deceze Sep 09 '22 at 10:13
  • @deceze - that's a great reference. Thank you. Bookmarked. – Rounin Sep 09 '22 at 10:13
  • I'm shocked you've never come across it before…!? – deceze Sep 09 '22 at 10:15
  • @deceze Oh, yeah, you're right. `\n` and ` ` is new line or line feed, `\r` and ` ` is carriage return. Though they seem to do the same thing in this particular situation. – Ouroborus Sep 09 '22 at 10:16
  • @deceze - Oh, I use MDN all the time - I meant that particular section on that page (which I didn't find in my repeated searches before posting the question above). – Rounin Sep 09 '22 at 10:20

1 Answers1

0

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="" />
Rounin
  • 27,134
  • 9
  • 83
  • 108