Today I learned two tricks for the replace() function in Javascript.
- Use $? for the found pattern, and
- use (parentheses) within your regular expression if you want to refer to what it matched by $number in the replacement.
I needed the sub-string '.A.' to be zero-padded into '.0A.' instead. However, I wasn't positive enough that the only character that needed zero-padding would be an A, so I wanted to match the general case of any single character between dots.
So that means I could match any single character between dots and give a long-winded message: output = input.replace(/\.(.)\./g, "replace> $& <replace "); or more to the point: output = input.replace(/\.(\w)\./g, ".0$1.");
I can use either '.' (traditional Unix regexp for a single character) or '\w' (PCRE for any non-whitespace character) to match A with my expected input.
No comments:
Post a Comment