Remove sequential <br> in div filled by CMS users via rich text editors

时光怂恿深爱的人放手 提交于 2020-01-25 12:52:47

问题


I have div-area which is filled by CMS users and sends data via a rich text editor. How can I remove sequential br tags more than two in a <div> using jQuery?

I tried parent(), closest() but it didn't work.

For example, a CMS user added this HTML code using a rich text editor.

<div class="cms-data">
<br>
<span>
<br><br><br><br><br><br>
<a href="/uploads/755/a1.xls" target="_blank">xls</span></a>
<br><br><br>
</span>
<br><br>
</div>

Edit: I added a class name to the <div>, cms-data.


回答1:


Here's one way to do it:

$("#starting-point").find("br").each(function() {
    if (this.previousSibling && this.previousSibling.nodeName.toUpperCase() == 'BR') {
        $(this).remove();
    }
});

That finds all of the br elements within the given container (in my case, the element with the id "starting-point"). Then it loops through them in document order. If we have one that has an immediate previous sibling that's a br element, we remove it. We leave it alone if the thing just in front of it is not a br element (such as a text node, or a non-br element). Note that this doesn't consider <br> <br> to be two consequtive elements, because there's a space between them.

Live Example | Source




回答2:


DOM!

When a <br> is encountered, it is removed. When text or an element is encountered, the next <br> is not removed. When an element is encountered, removeSequentialBR is called on it, too.

function removeSequentialBR(node) {
    var child = node.firstChild;
    var remove = true;

    while (child) {
        if (child.nodeType === 1) {
            if (child.nodeName === "BR") {
                if (remove) {
                    var newChild = child.nextSibling;
                    child.parentNode.removeChild(child);
                    child = newChild;
                    continue;
                }

                remove = true;
            } else {
                remove = false;
                removeSequentialBR(child);
            }
        } else if (child.nodeType === 3 && /\S/.test(child.nodeValue)) {
            remove = false;
        }

        child = child.nextSibling;
    }
}

Here’s a demo.




回答3:


You can use just a regular expression to parse the text and replace all occurences that doesnt fit

value = value.replace("/(<br>(\s)*){2,}/","<br><br>");

The 1000 is a magical high number, which should include all the <br>s; increase this value, if needed. Maybe there is an unlimited value? 0 maybe?

EDIT: Sorry for the bad answer. I fixed the expression. Now it works properly and does find all sets of possible occurences.



来源:https://stackoverflow.com/questions/19861184/remove-sequential-br-in-div-filled-by-cms-users-via-rich-text-editors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!