draftjs-to-html icon indicating copy to clipboard operation
draftjs-to-html copied to clipboard

Insert   in whitespaces

Open anish-stha opened this issue 5 years ago • 3 comments

Currently when I insert spaces in draftjs editor, draftToHtml(convertToRaw(editorState.getCurrentContent())) does not convert whitespaces to nbsp when not at the end/start of a block.

How do I put nbsp; in the middle of paragraph tags as well?

anish-stha avatar Dec 19 '18 06:12 anish-stha

@artemisIrelia : white spaces in middle of text is considered as white space only and not converted to  . It is required to convert to convert space ->   in start and end so that browser do not trim the content.

jpuri avatar Dec 19 '18 06:12 jpuri

@artemisIrelia if you display the parsed state into something other than a textarea (ie a div via html-to-react) you'll need to add this to your stylesheet in order to keep whitespaces from collapsing in paragraphs:

p {
  white-space: pre-wrap;
}

maierson avatar Jan 23 '19 12:01 maierson

I know this is an old issue (yet it is still marked as open), so a solution that I used for such a problem (where it trimmed the multiple whitespaces from the start or end of the blocks), was to use a simple regex to convert all whitespaces into a   code:

// If there is text get its value and send it to the consumer
const value: string = draftToHTML(convertToRaw(editor.getCurrentContent()));

// Convert every whitespace in the text into a ` ` HTML code 
// that adds the option to have multiple whitespaces one after another
const addedWhitespaceCharacters = value.replace(/\s(?=[\w\s\d])/g, " ");

onEditorChange(addedWhitespaceCharacters);

This will convert all the whitespaces that are followed by: another whitespace, a word or a digit.

pstevovski avatar Jan 12 '21 11:01 pstevovski