I am trying to use listings to display Javascript code. Following the replies to another question, I worked out the following code:

    keywords={break, case, catch, continue, debugger, default, delete, do, else, 
              finally, for, function, if, in, instanceof, new, return, switch, 
              this, throw, try, typeof, var, void, while, with},
    morekeywords={class, export, boolean, throw, implements, import, this},

\begin{lstlisting}[breaklines={true}, language={Javascript}, numbers=left]
var string = "This is special' string";
var alpha = document.selection;
str = str.replace(/[!.:?,;\"]/g, '');
dictionary_access ("" + t );
var alpha = document.selection;

However the displayed listing does not have proper formatting (whitespaces being highlighted outside the string). I guess it is because the string delimiters are not escaped properly.

listing output

Someone else also had a similar issue with Basic. I have tried replacing [b] in string=[b]" with [bd], [m] for both single and double quote. Also tried using string=[s]"" but no success.


1 Answer 1


It looks like what's going on is that listings is failing to recognize that the double quote in line 3 is inside a "string" (actually a regex, of course). As such, the double quote on line 3 opens a string literal that is closed by the first double quote on line 4, but then a new string literal is opened by the second double quote on line 4.

I think you should be able to fix this problem just by making / into a string delimiter. In other words, add


to your \lstdefinelanguage.

There shouldn't be any issues with the interaction of " and ' with /, since / doesn't need to be escaped in "...", and vice versa.

  • I tried this but now have the issue that the symbol for division doesn't work for example: number = number / 256; /* not a regex */ some_other_number = number / 2; Sep 11, 2019 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.