Search code examples
javascriptjqueryselectioncontenteditable

How to remove trailing whitespace of an element in contenteditable?


I been trying for sometime now , please find my work till now below.

/**
     * @param {any} container contenteditable container
     * @param {any} node  element contained inside the container for which we need to 
     * remove the space from
     */
    function removeTrailingSpace(container,node){
        if (typeof window.getSelection != "undefined") {
            var sel = window.getSelection(), range;
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0).cloneRange();
                range.collapse(true);
                range.setStartAfter(node);
                range.setEnd(container, 1);

                var rString = range.toString();
                var sChar = range.toString().length > 0 ? rString[0] : null;

                if (sChar && sChar.trim() === '') {
                    console.log("TRAILING SPACE FOUND");
                    range.setEnd(range.startContainer, range.startOffset + 1);
                    range.deleteContents();
                }
            }
        }
    }

To be more specific ,I need to remove "&nbsp" after button element from the contenteditable div.

enter image description here

Any Suggestion would be much appreciated . Thanks


Solution

  • I found a solution to your problem, the whitespace you are trying to remove is actually a text node. Please try the code below:

    function removeTrailingSpace(container, node) {
        const values = Array.from(container.childNodes.values());
        const value = values.find(x => x === node);
        const index = values.indexOf(value);
        const nextNode = container.childNodes[index + 1];
        if(nextNode.nodeValue.length === 1 && nextNode.nodeValue.charCodeAt(0) === 160) {
            console.log('Whitespace found, removing...');
            container.removeChild(nextNode);
        }
    }