2017-10-18 86 views
1

我如何可以修剪空格从Draft.jsDraft.js - 如何修剪内容

+0

'String.protoype.trim()'不起作用? – Dane

+1

使用Draft.js生成的内容不是纯文本,而是JSON对象,所以不能使用'String.prototype.trim()'修剪空白。 –

回答

0

生成的内容两端也许存在一个更优雅的解决方案,但是当我面对我这个代码解决它同样的问题:

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+$/,""); 
    } 
} 

在这里,我添加了哪些还没有这些方法的浏览器trimLefttrimRight方法。

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方法 - 在这里我用Modifier.replaceText UTIL删除空格字符。 工作示例 - https://jsfiddle.net/p5532ddw/

+1

这工作就像一个魅力。谢谢。 –