Home > Back-end >  How to Replace Items in HTML Input
How to Replace Items in HTML Input

Time:05-10

How do I target all • items in html code?

For Example I have this html code

<p>&bull; sentence with bullet in front of it</p>
<p>&bull; second sentence with bullet in front of it</p>

and i want to use this code below using html.replace to replace the &bull; string with an empty quotes. Not sure if im using regex the right way? thanks for your help!

       function replaceBullets(html) {
        return html.replace(/&bull;/, ""); //not sure if im writing these inputs correctly
    }

CodePudding user response:

<body>
    <div id="sectionToClear">
        <p>&bull; sentence with bullet in front of it</p>
        <p>&bull; second sentence with bullet in front of it</p>
        <p>&bull; second sentence with bullet in front of it</p>
        <p>&bull; second sentence with bullet in front of it</p>
    </div>
    

    <script>
        function replaceAllBulls() {
            let section = document.querySelector('#sectionToClear');
            section.innerHTML = section.innerHTML.replace(/\u2022/g, "");
        }
        replaceAllBulls();

    </script>
</body>

You can look for a div with id, for example sectionToClear and get it's inner HTML, then replace &bull; char (or \u2022) with "nothing". And don't forget to add /g (global)! If you don't add it, it will delete only the first item.

Also, you have wrong function syntax. Look at JS docs to learn more.

CodePudding user response:

This will work as well as using the character code, which is \u2022!

function replaceBullets() {
            const pElements = document.getElementsByTagName("p")
            for (let element of pElements) {
                element.innerText = element.innerText.replace(/(•|&bull;)/g, "")
            }
        }
<body onl oad="replaceBullets()">
    <p>&bull; sentence with bullet in front of it</p>
    <p>&bull; second sentence with bullet in front of it</p>
</body>

You can view how the regex works here.

  • Related