How to automatically replace predefined tags
P粉330232096
P粉330232096 2023-09-03 12:43:03
0
1
494
<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>
P粉330232096
P粉330232096

reply all(1)
P粉388945432

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 in replace will be the value. Loop through the rules and update the string.

const input = `Today is <day>th day of the month. 
I'd like <red> this text to be in red</red> 
and <blue>this to be in blue</blue>. 
Testing the links <a ###https://www.google.com/>with Google</>
and <a ###https://stackoverflow.com/>Stak Overflow</>`

function convert(str) {
  const replacerRules = new Map([
    [/<day>/g, new Date().getDate()],
    [/<([^>]+)>([^<]+)<\/>/g, (_, p1, p2) => `<span style="color: ${p1}">${p2}</span>`],
    [/<a #+([^>]+)>([^<]+)<\/>/g, (_, p1,p2) => `<a href="${p1}">${p2}</a>`]
  ])
  
  for (const [key, replacer] of replacerRules)
    str = str.replace(key, replacer)
  
  return str
}

console.log( convert(input) )
document.querySelector("div").innerHTML = convert(input)
<div />
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!