有没有在字符串中创建转义字符的模式? [英] Is there a pattern for creating escape characters in string?

查看:160
本文介绍了有没有在字符串中创建转义字符的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中创建一个字符串格式化程序,它使用反斜杠进行转义。创建格式化程序本身已经非常简单。我的问题是找到转义字符,并在格式化程序中进行转义。



此格式化程序将.Net格式化实现复制到Javascript中。基于以下注意事项: http://msdn.microsoft.com/en-us/library/ 26etazsy



例如:

 ## ## \\ ###。format(123456)==123#456; 

正则表达式一直存在问题,因为JS中不支持正则表达式否定。



我发现,我已经做了几个循环,有时在其他循环中,以解释转义。我有一个工作,但我正在寻找一个更加优雅,希望基于一个既定的模式。



有没有一个已建立的模式这样做? p>

解决方案

内置的方法是通过 replaceValue回调

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

函数mapper(match,offset,fullstring)
{
return offset;
}

#### \\ ## \\#。replace(/#(?=#| $)/ g,mapper).replace /\\./g,替代品); // 012#5#8


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?

解决方案

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

这篇关于有没有在字符串中创建转义字符的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆