import { isValidElement } from 'react'

const whitespacesRe = /\s+/g
const _format = (str = '') => str.trim().replace(whitespacesRe, ' ')

const elementToTextRec = x => {
  if (Array.isArray(x)) {
    return x.map(elementToTextRec).join('')
  } else if (isValidElement(x)) {
    return elementToTextRec(x.props.children)
  } else if (typeof x === 'string') {
    return x || ''
  }

  return ''
}

const elementToText = node => _format(elementToTextRec(node))

export default elementToText

import { isValidElement } from 'react'

const whitespacesRe = /\s+/g
const _format = (str = '') => str.replace(whitespacesRe, ' ')

const elementToTextRec = x => {
  if (Array.isArray(x)) {
    return x.map(elementToTextRec).join('')
  } else if (isValidElement(x)) {
    return elementToTextRec(x.props.children)
  } else if (typeof x === 'string') {
    return x || ''
  }

  return ''
}

const elementToText = node => _format(elementToTextRec(node)).trim()

export default elementToText

--- 
+++ 
@@ -1,7 +1,7 @@
 import { isValidElement } from 'react'
 
 const whitespacesRe = /\s+/g
-const _format = (str = '') => str.trim().replace(whitespacesRe, ' ')
+const _format = (str = '') => str.replace(whitespacesRe, ' ')
 
 const elementToTextRec = x => {
   if (Array.isArray(x)) {
@@ -15,6 +15,6 @@
   return ''
 }
 
-const elementToText = node => _format(elementToTextRec(node))
+const elementToText = node => _format(elementToTextRec(node)).trim()
 
 export default elementToText
Move trim into more sensible place