I have two identical strings in javascript with some spaces. When I printed the ascii values by using str.charCodeAt(n)
it is showing the values as 32 and 160. I googled the values and it is showing me as breaking and non breaking spaces. So can anybody explain what is this behaviour.
I have two identical strings in javascript with some spaces. When I printed the ascii values by using str.charCodeAt(n)
it is showing the values as 32 and 160. I googled the values and it is showing me as breaking and non breaking spaces. So can anybody explain what is this behaviour.
- Can you give us a sample of the 2 strings you used? – Mistalis Commented Aug 1, 2016 at 11:44
- Why is there a java tag? – CloudPotato Commented Aug 1, 2016 at 11:45
-
Points to ponder:
charCodeAt
gives you a UTF-16 code unit, one or two of which encode a Unicode codepoint. The ASCII character set does not have a non-breaking space character (but that's okay, if you are using JavaScript, Java, .NET, HTML, XML, …, you're probably not using ASCII.) – Tom Blodget Commented Aug 1, 2016 at 23:53
3 Answers
Reset to default 8The difference between a normal (breaking) space and a non-breaking space is that text display and typesetting software should not insert an automatic line break in place of a non-breaking space. (It is as if the non-breaking space joins the words before and after it into an unsplittable word.) By contrast, a regular space is treated as a possible place to break a line.
Having said that, the code 160
is actually outside of the range of regular (7-bit) ASCII. The interpretation of 160
as a non-breaking space (or NBSP
) character es from the Latin1 (ISO8859-1) character set. (In Extended ASCII, the code for the NBSP
character is 255
!)
References:
- "Non-breaking space" (Wikipedia)
- ASCII and Extended ASCII code charts
- "The Latin-1 (ISO8859-1) Character Set"
A non-breaking space is a space that will not break into a new line. Two words separated by a non-breaking space will stick together and not break into a new line.
Breaking spaces on the other hand will break.
Fun fact: SQL functions that operate on spaces (for example, LTRIM()) only operate on breaking spaces, not on non-breaking spaces. To get them to work on your character strings (say, for example, if you imported data where someone had used non-breaking spaces), you need to convert them to breaking spaces first.