Dealing with invalid js characters in VS Code
Even though mental stability is core personal principle that is rarely violated, here is something that was driving me mad recently.
[js] invalid character
With funny red squiggles thus
There was no rogue comma or strange character visible and no amount of deleting would resolve it. I’m more used to Visual Studio where odd things happen fairly frequently and this kind of thing can be ignored while the environment catches up with itself. However this floored VS Code and my lovely demo app just stop working. It was happening all the time. Bah!!
Although it isn’t visible in VS Code, the rogue character is visible in Chrome developer toolbar.
Press F12 -> Select Sources -> Navigate to the broken js file
The dodgy character is visible as a red dot and the character can be identified by hovering over it
In this case the character is
\u donates Unicode and the 7f is hexadecimal so converting to decimal the character is 127. Looking this up on an ASCII table we find out it is a [DEL] character.
Once the culprit is identified it’s an easier matter to use this regex
to find and replace the rogue character and replace it with an empty string. Don’t forget to do a regex search in VS code – select the star icon in the search box as show below. This fixes the application and thus repairs my fragile mental state.
How to write regex to find Unicode. The important point to remember is that it must contain 4 hexadecimal digits. So \u7f does find my DEL character – the regex needs to be padded out to \u007f
Download page for VS Code. Recommended.
I’m having this same problem in VS Code although my character is \u0 according to chrome developer tools. I haven’t seemed to be able to get rid of it via regex and this is recurring. It’s a big headache to me for sure. I am running a windows 10 laptop. I still can’t seem to match the character with \u0000. Maybe I’m getting the wrong character out of it? Is there a setting that must be there in order to be able to grab the character with regex? What a pain haha.
What worked for me was to delete all the code, and rewrite it by making sure I don’t press the keyboard key for the character bothering me (the regex search didn’t yield anything).
*all the problematic code.
Hello Sid, thanks for the reply. It turned out the culprit for me wasn’t Visual Studio Code, it was actually my nginx set up. Apparently running a virual machine with nginx and a sendfile on; can miraculously garble up any js/css files you edit on a server. A sudo service nginx restart fixes the problem but sendfile off is a better solution. It was really weird.
Thanks Richard. You saved me!