简体   繁体   中英

replace Specific text to html

how to replace or change specific text to new html?

Old HTML:

<div id="test">    
    <p>
        [b] lorem ipsum [/b]
    </p>
    <p>
        [textarea] lorem ipsum [/textarea] 
    </p>
</div>

New HTML:

<div id="test">
    <p>
        <b>lorem ipsum</b>
    </p>
    <p>
        <textarea>lorem ipsum</textarea>
    </p>
</div>
Force_Tag = [
    '[b]','<pre>',
    '[/b]','</b>',
    '[textarea]','<textarea>',
    '[/textarea]','</textarea>',
    // ...
]

You can use String.prototype.replace() with RegExp /(\\[)|(\\])/g to capture "[" , "]" , replace first capture group with "<" , second capture group with ">" , set .innerHTML of elements to replacement strings

 <div id="test"> <p> [b] lorem ipsum [/b] </p> <p> [textarea] lorem ipsum [/textarea] </p> </div> <script> for (let p of document.querySelectorAll("#test p")) { p.innerHTML = p.innerHTML.replace(/(\\[)|(\\])/g, function(match, p1, p2) { if (p1) return "<"; if (p2) return ">" }) } </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM