繁体   English   中英

Javascript地图/替换功能不替换方括号

[英]Javascript map / replacement function is not replacing square brackets

我创建了下面的函数,用[ 或 ]替换所有方括号。 该功能还包括其他一些按预期工作的替代品。

var desc = "[On Play] Reveal 5 cards from the top of your deck. Add 1 Tamer card among them to your hand. Place the remaining cards at the bottom of your deck in any order."

var mapObj2 = {
    "<":"[",
    ">":"]",
    "[":"<strong>[",
    "]":"]</strong>",
};

function replaceDesc(str,mapObj2){
    var re = new RegExp(Object.keys(mapObj2).join("|"),"gi");
    return str.replace(re, function(matched){
        return mapObj2[matched.toLowerCase()];
    });

desc = replaceDesc(desc,mapObj2);

我得到的输出是:

"[When Attacking] When you attack an opponent's Digimon, this Digimon gets +1000 DP for the turn."

我希望得到:

"<strong>[When Attacking]</strong> When you attack an opponent's Digimon, this Digimon gets +1000 DP for the turn."

这是一个工作示例,但我不得不说你在这里做的事情肯定很尴尬。 这似乎是一个不必要且令人困惑的抽象,我宁愿手动写出每组正则表达式映射,而不是使用这样的函数来处理它们。 我猜你正在对 HTML 类型的东西进行某种降价。

基本上你有两个问题。

  1. 您的方括号没有转义,方括号[]是正则表达式中的特殊字符,用于基本上做类似于| 特点。 所以,你必须用反斜杠\来逃避它们。
  2. 找到匹配项后,它将在没有转义字符的情况下返回给您,因此在替换函数中,我将其设置为返回与该键关联的对象(如果它不是未定义的),否则尝试添加转义字符。 如果您不这样做,当方括号匹配时,您的 mapObj2[baseKey] 将返回 undefined。
var desc =
  "[On Play] Reveal 5 cards from the top of your deck. Add 1 Tamer card among them to your hand. Place the remaining cards at the bottom of your deck in any order.";

var mapObj2 = {
  "&lt": "[",
  "&gt": "]",
  "\\[": "<strong>[",
  "\\]": "]</strong>",
};

function replaceDesc(str, mapObj2) {
  var re = new RegExp(Object.keys(mapObj2).join("|"), "gi");
  console.log(re);
  return str.replace(re, function (matched) {
    const baseKey = matched.toLowerCase();
    const altKey = "\\" + baseKey;

    return mapObj2[baseKey] || mapObj2[altKey];
  });
}

console.log(replaceDesc(desc, mapObj2));

编辑:如果您是 Regex 的新手,我建议您学习RegexOne

EDIT2:如果您想要一些也可以工作的东西(更清洁的imo),这是一个替代代码片段。 我不太清楚你在这里用&lt&gt做什么,所以我把它们拉了出来,但你应该可以用/</gi/>/gi组重新添加它们。 您可以使用RegExr来查看将匹配哪些不同的正则表达式。

function replaceStrong(str) {
  return str.replace(/\[/gi, "<strong>[").replace(/\]/gi, "]</strong>");
}

console.log(
  replaceStrong("[On Play] Reveal <5> cards from the top of your deck.")
);
// <strong>[On Play]</strong> Reveal <5> cards from the top of your deck.

正如@BenMcLean981 已经指出的那样:有一种更简单的方法。 这个片段演示了它:

 const desc = "[On Play] Reveal 5 cards from the top of your deck. Add 1 Tamer card among them to your hand. Place the remaining cards at the bottom of your deck in any order."; console.log(desc.replace(/\[.+?\]/g,"<strong>$&</strong>"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM