import re

re_js_comments_str = r"""
    (                               # Capture code
        (?:
            "(?:\\.|[^"\\])*"           # String literal
            |
            '(?:\\.|[^'\\])*'           # String literal
            |
            (?:[^/\n"']|/[^/*\n"'])+    # Any code besides newlines or string literals (essentially no comments)
            |
            \n                          # Newline
        )+                          # Repeat
    )|
    (/\* (?:[^*]|\*[^/])* \*/)      # Multi-line comment
    |
    (?://(.*)$)                     # Comment
"""
re_js_comments = re.compile(re_js_comments_str, re.VERBOSE + re.MULTILINE)


def strip_js_comments(string):
    """Originally obtained from Stackoverflow this function strips JavaScript
    (and JSON) comments from a string while considering those encapsulated by strings.

        Source: http://stackoverflow.com/questions/2136363/matching-one-line-javascript-comments-with-re
    """
    parts = re_js_comments.findall(string)
    # Stripping the whitespaces is, of course, optional, but the columns are fucked up anyway
    # with the comments being removed and it doesn't break things.
    return ''.join([x[0].strip(' ') for x in parts])