Recently need to implement a simple rich text box, the main functions are:

  • Insertion of expression
  • Send a bulletin to get the plain text content in the send box

Some implementation details

You can use div+ Contenteditable textarea simulation to set the spellCheck property to turn spell checking off and the red wavy lines are no longer displayed

<div contenteditable="true" spellcheck="false"This is an editable paragraph. Please try editing the text. </div>Copy the code

Note: Internet Explorer 9 and earlier Versions of IE do not support the spellCheck property.

Uniform style for inserting text

When I wrap a line in an editable div, I find that



will be inserted and continue typing, replacing

with what we typed.

Here’s the idea:

  • 1. ListeningpasteThe event
  • 2. Then fromclipboardDataThrough thegetData('text')Method to get content
  • 3. Match newlines and Spaces in the plain text with regex
  • 4. Useevent.preventDefault()Cancel the default paste operation, manually insert our format after the data
target.addEventListener('paste', (event) => {// Use 'window.clipboardData' instead of 'event.clipboardData' in IElet paste = (event.clipboardData || window.clipboardData).getData('text'); // Format the retrieved data and insert it manually //... event.preventDefault(); });Copy the code

Add: I had another idea at first, to get the HTML string from getData(‘text.html’), and then replace the tags with regular matches to remove the attributes and styles, but the match was not perfect enough, and my requirements were relatively simple, so I chose the above implementation.

Magic space

I always thought space was. The result in the re matches xxx.replace(‘/\s/g’, ‘  ‘) after finding the page directly put   It shows up. Looking up the data, I found that there were two kinds of Spaces.

Unicode Decimal value describe The Latin alphabet
U+0020 160 The blank space Basic Latin alphabet
U+00A0 32 No newline Spaces Latin letter -1 auxiliary

We click the space bar through the keyboard to input space, namely U+0020, ordinary half-corner space, displayed as blank characters.

Another type of U+00A0 is called a nonnewline space. The purpose is to disallow line breaks. In HTML page display, will automatically merge multiple consecutive white space characters; However, if non-newline Spaces are used, merging is prohibited, so they are also called hard Spaces. In the web page display, its escape character is  

// For examplelet dom = document.querySelector('div') // Automatically merge the space dom.innertext ='y u'
dom.innerText = 'y\u0020\u0020u'Dom.innertext. Length // 3 // Disallow merging dom.innertext ='u\u00a0\u00a0i'// Or use the space escape character & NBSP; InnerHTML // or dom.innerhtml ='u    i'
dom.innerText.length // 4
Copy the code

Tips: use & have spent Only setting it to innerHTML works. Setting textContent, innerHTML, and innerText works with \ u00A0.