简体   繁体   English

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

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

I have created the function below to replace all square brackets with either [ or ] .我创建了下面的函数,用[ 或 ]替换所有方括号。 The function also includes some other replacements that are working as expected.该功能还包括其他一些按预期工作的替代品。

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);

The output I am getting is:我得到的输出是:

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

I expected to get:我希望得到:

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

Here is a working example, but I have to say what you're doing here is definitely awkward.这是一个工作示例,但我不得不说你在这里做的事情肯定很尴尬。 It seems like an unnecessary and confusing abstraction, I would prefer to write out each set of regex mappings manually instead of having a function like this to handle them.这似乎是一个不必要且令人困惑的抽象,我宁愿手动写出每组正则表达式映射,而不是使用这样的函数来处理它们。 I'm guessing you're making some sort of markdown to HTML type of thing.我猜你正在对 HTML 类型的东西进行某种降价。

Basically you have two issues.基本上你有两个问题。

  1. Your square brackets are not escaped, the square bracket [] are special characters in regex used for basically doing something similar to the |您的方括号没有转义,方括号[]是正则表达式中的特殊字符,用于基本上做类似于| character.特点。 So, you have to escape them with a backslash \ .所以,你必须用反斜杠\来逃避它们。
  2. Once you've found a match, it's going to come back to you without the escape character, so inside the replace function I have it setup to return the object associated with that key if it's not undefined, otherwise try adding an escape chararcter.找到匹配项后,它将在没有转义字符的情况下返回给您,因此在替换函数中,我将其设置为返回与该键关联的对象(如果它不是未定义的),否则尝试添加转义字符。 If you don't do this, your mapObj2[baseKey] will return undefined when the square braces match.如果您不这样做,当方括号匹配时,您的 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));

EDIT: If you're new to Regex, I'd recommend RegexOne to learn.编辑:如果您是 Regex 的新手,我建议您学习RegexOne

EDIT2: Here's an alternative code snippet if you want something (a bit cleaner imo) that also works. EDIT2:如果您想要一些也可以工作的东西(更清洁的imo),这是一个替代代码片段。 It's not super clear to me what you're doing with &lt and &gt here so I pulled them, but you should be able to add them back with a /</gi or />/gi group.我不太清楚你在这里用&lt&gt做什么,所以我把它们拉了出来,但你应该可以用/</gi/>/gi组重新添加它们。 You can play around with RegExr to see what different regular expressions will match.您可以使用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.

As @BenMcLean981 already remarked: there is an easier way of doing it.正如@BenMcLean981 已经指出的那样:有一种更简单的方法。 This snippet demonstrates it:这个片段演示了它:

 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