Is there a pattern for creating escape characters

2019-04-12 16:02发布

问题:

I am creating a string formatter in javascript that uses backslashes for escapes. Creating the formatter itself has been pretty easy. My issue is finding the escape characters, and doing the escapes in the formatter.

This formatter copies the .Net formatting implementation into Javascript. Based off these notes: http://msdn.microsoft.com/en-us/library/26etazsy

For example:

"####\\###".format(123456) == "123#456";

Regex has been problematic because regex negation is not supported in JS.

What I'm finding is that I have do to several loops, sometimes within other loops, to account for the escapes. I've got it working, but I'm looking for a more elegant, hopefully based off an established pattern.

Is there an established pattern for doing so?

回答1:

The built-in way to do this is via a replaceValue callback:

function replacer(match, offset, fullstring)
  {
  return match.substr(-1);
  }

function mapper(match, offset, fullstring)
  {
  return offset;
  }

"####\\##\\#".replace(/#(?=#|$)/g, mapper).replace(/\\./g, replacer); //012#5#8