How to automatically replace predefined tags
P粉330232096
2023-09-03 12:43:03
<p>I have some characters that need to be replaced as above, but I don't know how: </p><p>
Characters to replace: </p>
<pre class="brush:php;toolbar:false;">first | end |
<day> | |
<red> | </red>|
<a ###> | </> |</pre>
<p><code>day => Get the current date (for example: 14)</code></p><p>
<code>red => color red</code> </p><p>
<code><a ###https://www.google.com/>Link</> => <a href="https://www.google.com/"> Link</></code></p>
<p><code>Enter: Hello<red>Mr. Siro</red></code> </p><p>
<code>Output: Hello<span style="color: red">Mr. Siro</span></code></p>
<p>My chat history. </p>
<p>Can you tell me how to write a generic function to check for replacement of the above tag?
This is my code: </p>
<p>
<pre class="snippet-code-js lang-js prettyprint-override"><code>export const formatTags = (content) => {
const firstTag = "<red>";
const secondTag = "</red>";
const tagsIndex = [...content.matchAll(new RegExp(firstTag, "gi"))].map(
(a) => a.index
);
const initialContent = content;
tagsIndex.forEach((index) => {
const tagContent = initialContent.substring(
index firstTag.length,
initialContent.indexOf(secondTag, index)
);
if (firstTag === "<red>") {
content = content.replaceAll(
`${firstTag}${tagContent}${secondTag}`,
`<span style="color: red">${tagContent || "わからない"}</span>`
);
}
});
return content;
};</code></pre>
</p>
<p>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span
:class="(msg.image || msg.file) && msg.text ? 'mt-2' : ''"
v-html="msg.text"
v-linkified:options="{
className: currentUserId === msg.senderId
? 'message-external-link'
: '',
}"
/></code></pre>
</p>
<p>Sorry my English is not very good! </p><p>
thank you all! </p>
You can create a
Map
of replacement rules. The regular expression used to capture the text will be the key and the replace function callback used inreplace
will be the value. Loop through the rules and update the string.