He creado la siguiente función para reemplazar todos los corchetes con [o] . La función también incluye algunos otros reemplazos que funcionan como se esperaba.
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);
La salida que obtengo es:
"[When Attacking] When you attack an opponent's Digimon, this Digimon gets +1000 DP for the turn."
esperaba obtener:
"<strong>[When Attacking]</strong> When you attack an opponent's Digimon, this Digimon gets +1000 DP for the turn."
Aquí hay un ejemplo de trabajo, pero tengo que decir que lo que estás haciendo aquí es definitivamente incómodo. Parece una abstracción innecesaria y confusa, preferiría escribir cada conjunto de asignaciones de expresiones regulares manualmente en lugar de tener una función como esta para manejarlas. Supongo que estás haciendo algún tipo de descuento en el tipo de HTML.
Básicamente tienes dos problemas.
[]
son caracteres especiales en expresiones regulares que se usan básicamente para hacer algo similar a |
personaje. Por lo tanto, debe escapar de ellos con una barra invertida \
. 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"); 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));
EDITAR: si es nuevo en Regex, le recomendaría RegexOne para aprender.
EDIT2: aquí hay un fragmento de código alternativo si quieres algo (un poco más limpio en mi opinión) que también funcione. No me queda muy claro lo que está haciendo con <
y >
aquí, así que los saqué, pero debería poder volver a agregarlos con un grupo /</gi
o />/gi
. Puede jugar con RegExr para ver qué diferentes expresiones regulares coincidirán.
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.
Como @BenMcLean981 ya comentó: hay una manera más fácil de hacerlo. Este fragmento lo demuestra:
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>"));