【问题标题】:How can I use JSON keys as regex?如何使用 JSON 键作为正则表达式?
【发布时间】:2017-02-26 12:29:33
【问题描述】:

我想要以下 JSON 对象:

let emotes = {
  /:-?\)/: 'smiley.png',
  /:-?\(/: 'sady.png',
  /:-?o/i: 'surprisey.png'
}

我想用这样的文本中的值替换键:

Object.keys(emotes).forEach(function(emote) {
  content = content.replace(emote, '<img src="smileys/' + emotes[emote] + '">')
})

这不起作用。这样做的正确方法是什么?

【问题讨论】:

  • 属性名只能是字符串。您可以使用字符串,然后根据需要构造 RegExp 实例。
  • “我有以下 JSON 对象”——不,你没有。这对于 Javascript 文字和 JSON 都是无效的语法。
  • 没错,我更新我的句子。
  • 那么您是否尝试使用其 ascii 格式作为键来查找相应的笑脸图像?
  • @shanks 是的,我是!

标签: javascript json regex


【解决方案1】:

我个人会使用数组。这允许您使用正则表达式常量并避免从字符串构造 RegExp 实例,并且还可以保证应用程序的顺序:

let emotes = [
  [ /:-?\)/, 'smiley.png' ],
  [ /:-?\(/, 'sady.png' ],
  [ /:-?o/i, 'surprisey.png' ]
];

然后:

emotes.forEach(function(pair) {
  content = content.replace(pair[0], '<img src="smileys/' + pair[1] + '">');
});

如果你不想要数字索引的丑陋(在我看来是轻微的,但对每个人来说都是他自己的)丑陋,你可以使用一个对象数组:

let emotes = [
  { pattern: /:-?\)/, src: 'smiley.png' },
  { pattern: /:-?\(/, src: 'sady.png' },
  { pattern: /:-?o/i, src: 'surprisey.png' }
];

【讨论】:

  • @SteeveDroz 是的,使用Object.keys() 进行迭代通常会按照“正确”的顺序进行,但这不是我个人喜欢依赖的那种东西,尤其是当安排担保通常非常简单。
【解决方案2】:

需要明确的是,这不是 JSON 对象。它甚至不是合法的 JavaScript 对象字面量。 JS 对象以字符串为键,而不是正则表达式。你所做的在 Firefox AFAICT 中是不合法的,可能是其他浏览器。检查您的浏览器日志,它可能会完全拒绝您对emotes 的定义。

如果您想使用一堆对,请创建一个对数组并使用它:

let emotes = [
  [/:-?\)/, 'smiley.png'],
  [/:-?\(/, 'sady.png'],
  [/:-?o/i, 'surprisey.png'],
]

emotes.forEach(function(emotereplacement) {
    var [emote, replacement] = emotereplacement;
    content = content.replace(emote, '<img src="smileys/' + replacement + '">');
});

【讨论】:

    【解决方案3】:

    您可以将“键”转换为字符串,使其成为有效的 JSON 对象。此外,语法是 Object.keys,而不是 Objects.getKeys。

    查看下面的工作 sn-p。

    let emotes = {
      ":-?)" : 'smiley.png',
      ":-?(": 'sady.png',
      ":-?o": 'surprisey.png'
    }
    
    var content = "  :-?)   :-?(  :-?o";
    
    Object.keys(emotes).forEach(function(emote) {
      content = content.replace(emote, '<img src="smileys/' + emotes[emote] + '">')
    })
    console.log(content);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 2018-03-21
      • 2021-05-22
      • 1970-01-01
      • 2011-10-30
      相关资源
      最近更新 更多