I want to record my editor's word count in metrics. Is there a cleaner way of extracting the number than first rendering:
<WordCounter ref="counter" editorState={this.state.editorState} />
and then:
this.refs.counter.getWordCount(this.refs.counter.props.editorState);
// feels like I'm peeking too deep into the plugin
// or
ReactDOM.findDOMNode(this.refs.counter).innerText;
// feels like I'm trusting the DOM too much
Any thoughts @adrianmc since you wrote the original plugin in #102?
@avk you could create create a counter with the custom counterFunction, use the word count code + extend it with firing to the metrics.
Does that help? I will close the issue for now, but feel free to ask more questions. I will reply.
For Googlers like me looking for a quick solution:
getWordCount(editorState) {
const plainText = editorState.getCurrentContent().getPlainText('');
const regex = /(?:\r\n|\r|\n)/g; // new line, carriage return, line feed
const cleanString = plainText.replace(regex, ' ').trim(); // replace above characters w/ space
const wordArray = cleanString.match(/\S+/g); // matches words according to whitespace
return wordArray ? wordArray.length : 0;
}
works for me, taken from https://github.com/draft-js-plugins/draft-js-plugins/blob/1da9943359a7e3dd9076daef2b4bea9de0e34eae/draft-js-counter-plugin/src/WordCounter/index.js
Most helpful comment
For Googlers like me looking for a quick solution:
works for me, taken from https://github.com/draft-js-plugins/draft-js-plugins/blob/1da9943359a7e3dd9076daef2b4bea9de0e34eae/draft-js-counter-plugin/src/WordCounter/index.js