Replace word at cursor

by th3uiguy

HTML

<div class="form">
  <input id="textArea" type="text" value=" Some sample text " onclick="outputWord()" onkeyup="outputWord()" />
  <button onclick="autoComplete.replaceAtCaret('YO!')">Replace</button>
  <div class="resultDiv">
    Result: <span id="result"></span>
  </div>
</div>

SCSS

.form{
	padding: 10px;
	input{
		font-size: 15px; 
	}
  
  .resultDiv{
    margin-top: 8px;
    color:#aaa;
    
    #result{
      color:#000;
    }
  }
}

JavaScript 1.7

class AutoComplete{
	constructor(element){
  	this.elem = element;
  }
  
	static getWord(text, caretPos) {
    const preText = text.substring(0, caretPos);
    const aftText = text.substring(caretPos);
    const charAft = aftText && aftText.charAt(0);
    const hasCharsAfter = charAft && charAft.match(/\S/);

    if (preText && preText.charAt(preText.length -1) || hasCharsAfter) {
      const preWords = preText.split(/\s/);
      let word = preWords[preWords.length - 1];
      if(hasCharsAfter){
        const aftWords = aftText.split(/\s/);
        word += aftWords[0];
      }
      return word;
    }
    return preText || "";
  }
  
  static getWordRange(text, pos){
  	const preText = text.substring(0, pos);
    const start = preText.length === 0? -1 : preText.lastIndexOf(" ");
    const word = AutoComplete.getWord(text, pos);
  	return {
    	start,
      word,
      length: word.length, 
    }
  }

  replaceAtCaret(value){
		this.selectAtCaret();
    
    //IE support
    if (document.selection) {
      sel.text = value;
    }
		// Other browsers
    else if (this.elem.selectionStart != null) {
      const startPos = this.elem.selectionStart;
      const endPos = this.elem.selectionEnd;
      this.elem.value = this.elem.value.substring(0, startPos)
          + value
          + this.elem.value.substring(endPos, this.elem.value.length);

      if(this.elem.setSelectionRange){
        const pos = startPos + value.length;
        this.elem.focus();
        this.elem.setSelectionRange(pos, pos);
      }
    }
    else {
      this.elem.value += value;
    }

  }
  
  selectAtCaret(){
  	const caretPos = AutoComplete.getCaretPosition(this.elem);
		const range = AutoComplete.getWordRange(this.elem.value, caretPos);
    const end = range.start + range.length;
    
    this.elem.focus();
    this.elem.setSelectionRange(range.start+1, end+1);
  }

  static getCaretPosition(elem) {
    let caretPos = 0;   // IE Support
    if (document.selection) {
      elem.focus();
...