V
V
vasyok2282021-09-28 23:37:31
JavaScript
vasyok228, 2021-09-28 23:37:31

js regular expression how to format html correctly?

Hello. Today I've been studying regular expressions all day, and I could not solve the problem. I will try to explain with examples.

There is at the entrance:

<div class="dialog__row_1">{FFFFFF}Склад:{33CCCC}%d {FFFFFF}из {33CCCC}%d</div>
<div class="dialog__row_2">Продуктов:%s</div>
<div class="dialog__row_2">{FFFFFF}Введите сколько желаете заказать:</div>


1. It is necessary that the regular expression replace {FFFFFF} with and set the closing one before the next {33CCCC} , and so go through all the colors. 2. Now the most difficult thing, dialog__row_1 has the last color {33CCCC} and it should work . But dialog__row_2 did not specify a color in {}, so you need to duplicate the last color from dialog__row_1 As it should be in the final:
<span style="color:#FFFFFF">
</span>



<span style="color:#33CCCC">%d</span>



<div class="dialog__row_1">
  <span style="color:#FFFFFF">Склад: </span>
  <span style="color:#33CCCC">%d </span> 
  <span style="color:#FFFFFF">из </span> 
  <span style="color:#33CCCC">%d</span> // Пункт 1
</div>
<div class="dialog__row_2">
  <span style="color:#33CCCC">Продуктов: %s</span> // Цвет взят из пункт 1
</div>
<div class="dialog__row_2">
  <span style="color:#FFFFFF">Введите сколько желаете заказать:</span>
</div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2021-09-29
@vasyok228

str.replace(
    /(?:(?<=<div\s+class="dialog__row_\d+">)|{([A-F\d]{6})})\s*([^\s<{][^<{]*)/g, 
    function () {
        arguments.callee.color = arguments[1] || arguments.callee.color; 
        return `<span style="color:#${arguments.callee.color}">${arguments[2]}</span>\n`
    }
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question