【问题标题】:What is the JS equivalent to the Ruby :tr method?什么是 JS 等价于 Ruby :tr 方法?
【发布时间】:2020-02-28 16:10:19
【问题描述】:

在 ruby​​ 中我可以这样做:

def DNA_strand(dna)
  base_hash = { 'A' => 'T', 'T' => 'A', 'G' => 'C', 'C' => 'G' }
  dna.gsub(/[ATGC]/, base_hash)
end

我也可以这样做,这将完全等效:

def DNA_strand(dna)
  Dna.tr(’ACTG’, ’TGAC’)
end

在 JS 中是否有与 :tr 在 ruby​​ 中等效的方法?

目前我只能想到这样在JS中解决这个问题:

function DNAStrand(dna){
  function matchBase(match, offset, string) {
    const base = { 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G' };
    return `${base[match]}`;
  }
  return dna.replace(/[ATGC]/g, matchBase);
}

任何 cmets 将不胜感激!

【问题讨论】:

  • 顺便说一句,return base[match]; 就够了。
  • 没有内置,但您可以将替换缩短为 dna.replace(/[ATGC]/g, m => base[m]),它仅比 ruby​​ 版本长一点。
  • 这是 Ruby 方法 String#tr 的文档。我希望任何不了解 Ruby 的人都想在冒险回答之前阅读一下。

标签: javascript regex ruby string string-substitution


【解决方案1】:

是的,在您的浏览器控制台中尝试一下

>> "FOOACTGBARACTG".replace(/ACTG/g, 'TGAC')

你会得到

<- "FOOTGACBARTGAC"

【讨论】:

  • 那只会将ACTG 替换为TGAC。 Ruby 的 tr 方法的工作方式不同,请参阅此处的文档 ruby-doc.org/core-2.6.3/String.html#method-i-tr。摘要:返回 str 的副本,其中 from_str 中的字符替换为 to_str 中的相应字符。如果 to_str 比 from_str 短,则用最后一个字符填充以保持对应关系。
猜你喜欢
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多