@ # box

by Sasá Rafalsky

HTML

CONTENTEDITABLE (@, #)

<br><br><br>

<div class="richEditor">
  <div id="output"></div>
  <div id="input" contenteditable="true"></div>
</div>

SCSS

.richEditor {
  width: 360px;
  min-height: 120px;
  border: 1px solid #000;
  border-radius: 5px;
  position: relative;
  box-sizing: border-box;
  display: block;
  
  #input {
    top: 0;
    position: absolute;
    color: rgba(0,0,0,0.25);
    width: 100%;
    height: 100%;
    z-index: 1;
  }
  
  #output {
    top: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    color: red;
  }
  
  .hash {
    color: #fff;
    background: #09f;
    border-radius: 3px;
  }
  
  .mention {
    color: #fff;
    background: #f00;
    border-radius: 3px;
  }
}

JavaScript

$(document).ready(function() {
  $('#input').on('input keyup', converter);
  $('div[contenteditable]').keyup(function(e) {
    if (e.keyCode === 13) {
    	console.log("ENTER PRESSED");
      return '$';
		} else if (e.keyCode === 32) {
    	//console.log("Space");
    }
    
    converter();
  });

  //converter();
});

function converter() {
	var input = document.getElementById("input");
  var output = document.getElementById("output");
  var str = input.textContent;
      str = str.replace(/(<)/gi, '&lt;');
      str = str.replace(/(<)/gi, '&lg;');
      str = str.replace(/(?:\r\n|\n\r|\r|\n)/g, '<br><br>');
      str = str.replace(/#(.+?)(?=[\s.,:,]|$)/g, '<span class="hash">#$1</span>');
      str = str.replace(/@(.+?)(?=[\s.,:,]|$)/g, '<span class="mention">@$1</span>');
      str = str.replace(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/g, '<span>$1</span>');
  
  output.innerHTML = str;
}