I'm sure that I'm missing something fundamental, but I am not sure what.
Here is some code:
var carColor = JSON.stringify(this.car.color);
document.getElementById('id').innerHTML = carColor; // displays: "blue"
console.log(carColor); // displays: '\'blue\''
I assume I can use a function to remove the slashes from that text, but is there a better way to get that variable to just be equal to the color name?
The behaviour of JSON.stringify()
is standardized and does not add the slashes you are observing.
However, the precise behaviour of console.log()
is not standardized across platforms, and can vary. A proposed specification is in development, but that's still in its very early stages (and it's still not clear to me whether it will cover this detail). You cannot rely on its output being entirely consistent.
On some platforms, strings may be automatically re-escaped before they're displayed, so that any special characters are clear to the reader (who is assumed to be a developer, not an end user who would be confused). When the string has already been escaped with JSON.stringify()
, this double-escaping can results in backslashes being shown in the output, as you've experienced.
You can use another method of displaying text such as alert()
to verify the actual contents of your string.