Search code examples
reactjsdraftjs

Draft.js - How to trim contents


How can I trim whitespace from both ends of contents generated with Draft.js


Solution

  • Maybe exist a more elegant solution, but when I faced with the same problem I solved it with this code:

    if(typeof String.prototype.trimLeft !== 'function') {
        String.prototype.trimLeft = function() {
            return this.replace(/^\s+/,"");
        }
    }
    
    if(typeof String.prototype.trimRight !== 'function') {
        String.prototype.trimRight = function() {
            return this.replace(/\s+$/,"");
        }
    }
    

    Here I add trimLeft and trimRight methods for browsers which have not these methods.

    trimContent = () => {
      const editorState = this.state.editorState;
      let currentContent = this.state.editorState.getCurrentContent();
      const firstBlock = currentContent.getBlockMap().first();
      const lastBlock = currentContent.getBlockMap().last();
      const firstBlockKey = firstBlock.getKey();
      const lastBlockKey = lastBlock.getKey();
      const firstAndLastBlockIsTheSame = firstBlockKey === lastBlockKey;
    
      const textStart = firstBlock.getText()
      const trimmedTextStart = textStart.trimLeft();
      const lengthOfTrimmedCharsStart = textStart.length - trimmedTextStart.length;
    
      let newSelection = new SelectionState({
        anchorKey: firstBlockKey,
        anchorOffset: 0,
        focusKey: firstBlockKey,
        focusOffset: lengthOfTrimmedCharsStart
      });
    
      currentContent = Modifier.replaceText(
        currentContent,
        newSelection,
        '',
      )
    
      let newEditorState = EditorState.push(
        editorState,
        currentContent,
      )
    
      let offset = 0;
    
      if (firstAndLastBlockIsTheSame) {
        offset = lengthOfTrimmedCharsStart
      }
    
      const textEnd = lastBlock.getText()
      const trimmedTextEnd = textEnd.trimRight();
      const lengthOfTrimmedCharsEnd = textEnd.length - trimmedTextEnd.length
    
      newSelection = new SelectionState({
        anchorKey: lastBlockKey,
        anchorOffset: trimmedTextEnd.length - offset,
        focusKey: lastBlockKey,
        focusOffset: textEnd.length - offset
      });
    
      currentContent = Modifier.replaceText(
        currentContent,
        newSelection,
        '',
      )
    
      newEditorState = EditorState.push(
        editorState,
        currentContent,
      )
    
      this._handleChange(newEditorState);
    }
    

    trimContent method - here I used Modifier.replaceText util for deleting space characters. Working example - https://jsfiddle.net/p5532ddw/