0

I'm pretty stumped as to what's wrong with the following regular expression:

var // this regex digests a string into leading whitespace,
    // content text, and trailing whitespace.
    lineRegex = /^(\s*)(\S.*\S|\S)?(\s*)$/g,
    /* ... */;

lineRegex is supposed to match anything. There is not even one required character, and if there are characters in the string, they are all either white space or not white space. When I paste the exact regex into FireBug console and add .exec(""), I get the expected result, ["", "", undefined, ""]. But in my JSFiddle (http://jsfiddle.net/Lay9k/9/) I have:

try {
    var sections = lineRegex.exec(lineTxt),
        rawLeadingWs = sections[1] || "",
        contentText = sections[2] || "",
        importantTabs = rawLeadingWs.replace(
            oneTabWorthOfSpaces, "\t"
        ),
        tabsAndAligningSpaces =
            aligningTabRegex.exec(importantTabs),
        // I don't like this as much as Lint does.
        importantWsLength = 
            (tabsAndAligningSpaces[1] || "").replace(/[^\t]/g, "")
            .length * spacesPerTab +
            (tabsAndAligningSpaces[2] || "").length;
} catch (wtf) {
    console.log({
        lineText: lineTxt,
        sections: sections,
        rawLeadingWs: rawLeadingWs,
        contentText: contentText,
        importantTabs: importantTabs,
        tabsAndAligningSpaces: tabsAndAligningSpaces,
        importantWsLength: importantWsLength
    });
    throw wtf;
}

and I get sections is null when lineTxt is "". So what gives?

sqykly
  • 1,586
  • 10
  • 16
  • why use regex if you want to match anything? – Anirudha Jan 29 '14 at 06:35
  • @Anirudh I want it to match everything - the important part is the captures. It divides the string into leading whitespace (`[1]`), content (`[2]`), and trailing whitespace (`[3]`). – sqykly Jan 29 '14 at 06:38
  • @Anirudh (and that's beside the point - it isn't matching anything anyway) – sqykly Jan 29 '14 at 06:39

1 Answers1

0

I think the problem is that the lastIndex property of the regex is not reset properly.

Here's a related issue: Why does Javascript's regex.exec() not always return the same value?

reg.lastIndex = 0; from one of the answers seems to fix it.

Community
  • 1
  • 1
Hans
  • 2,610
  • 3
  • 17
  • 20