0

I've noticed an issue I've never encountered before. Strings in JavaScript that contain < are ignored. Why is that? Here are a few of the results I've noticed:

msg = "<This entire string would be ignored."
msg = "This part of the string is ok. <While this part is ignored."
msg = "<This part is ignored> But this half of the string will still print."

Is this some kind of special escape character or something? What is it used for? Additionally, what would be a work around for this?

Here is code:

var msg = "This is my message <This is ignored";
document.write(msg);

6
  • I don't see the character is getting escaped. Tried in chrome developer console. Commented Oct 14, 2017 at 7:32
  • Can't replicate. Could you add a demo? Commented Oct 14, 2017 at 7:33
  • 1
    You set the innerHTML of an element with that string, right? Don't do that. You want to set the textContent. Commented Oct 14, 2017 at 7:36
  • < is used to indicate HTML tags, like <div>, <a>, etc. Commented Oct 14, 2017 at 7:40
  • Gotcha, Thanks. I wouldnt think it would do that when contained inside a string? Commented Oct 14, 2017 at 7:42

2 Answers 2

2

This is not an issue with JavaScript; it's an issue with your code. Here's the problem, as suggested by @Tomalak.

You are using innerHTML as opposed to textContent, which will try to parse the string as a tag with attributes, for example.

<This part is ignored><this> with the part, is, and ignored attributes

Sign up to request clarification or add additional context in comments.

1 Comment

It appears that you had a question about it not happening in a string. JavaScript interprets the string, as a string; when you set the innerHTML the browser converts it to HTML, but it is still a string in your code. For example: var msg = '<brendan>'; document.body.innerHTML = msg; console.log(msg);
1

When you write something with document.write(), it's simply inserted into the HTML source of the page at that location. As a result, if there are any HTML tags in it, they will be parsed. Anything that begins with < is treated as an HTML tag. If you want to write a literal <, use &lt;:

var msg = "This is my message &lt;This is NOT ignored";
document.write(msg);

You really shouldn't use document.write() in the first place, that's 1990's Javascript; assign to innerHTML or textContent of an element. innerHTML will be parsed as HTML, textContent will be treated as literal text and not parsed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.