Reputation: 23
I got a task to write code highlighter for C#. Everything's pretty good, but I wish to optimize indentation. So, I have a regexp looking like /(\t|[ ]{4})/g
, so I replace tabulation or 4 space chars with <span style="margin-left: 2em;" />
and it looks good, but it creates a lot of unnecessary spans. I want to use something like /^[ ]{x}/g
and replace with <span style='margin-left: "+(0.5*x)+"em;' />
to have only one span per line with appropriate margin. str.match()
won't work because it searches in all document, not per line.
Upvotes: 0
Views: 352
Reputation: 129139
If your regular expression has the g
flag, you can execute it over and over again, getting all matches from the string, including the length of the match:
var re = /^(\t|[ ]{4})/g;
var match;
while((match = re.exec(text)) {
// use match.index and match[0].length
}
Upvotes: 2