1
我如何可以修剪空格從Draft.jsDraft.js - 如何修剪內容
我如何可以修剪空格從Draft.jsDraft.js - 如何修剪內容
生成的內容兩端也許存在一個更優雅的解決方案,但是當我面對我這個代碼解決它同樣的問題:
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+$/,"");
}
}
在這裏,我添加了哪些還沒有這些方法的瀏覽器trimLeft
和trimRight
方法。
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/
這工作就像一個魅力。謝謝。 –
'String.protoype.trim()'不起作用? – Dane
使用Draft.js生成的內容不是純文本,而是JSON對象,所以不能使用'String.prototype.trim()'修剪空白。 –