Textarea Escape

by Ben Gillbanks

HTML

<div id="container"></div>

<div class="content">
<textarea id="source">This is some text <3</textarea>
<button id="update">Update</button>
</div>

CSS

#container {
    padding: 20px;
}
.content {
    background:orange;
    padding:20px;
}
textarea {
    width: 100%;
    height: 10rem;
}

JavaScript

var container = document.getElementById('container');
var textSource = document.getElementById('source');
var updateButton = document.getElementById('update');

updateButton.addEventListener(
    'click',
    (e) => {
        var text = sanitize.attr( textSource.value );
        updateContainer(text);
        //console.log(textSource.value);
    }
);


function updateContainer( text ) {

	console.log(text);
    var text = `<textarea>${text}</textarea>`;
    container.innerHTML = text;

}







/**
 * Sanitize stuff.
 *
 * see: https://stackoverflow.com/questions/1637275/simple-html-sanitizer-in-javascript
 */
const sanitize = {

	elem: null,


	/**
	 * Initialize sanitization.
	 *
	 * @return {void}
	 */
	init: function() {

		if ( !this.elem ) {
			this.elem = document.createElement( 'div' );
		}

	},


	/**
	 * Sanitize html string.
	 *
	 * @param {string} text
	 * @return {string}
	 */
	html: function( text ) {

		if ( '' === text ) {
			return text;
		}

		sanitize.init();

		this.elem.textContent = text;
		return this.elem.innerHTML;

	},


	/**
	 * Sanitize html string.
	 *
	 * @param {string} text
	 * @return {string}
	 */
	attr: function( text ) {

		if ( '' === text ) {
			return text;
		}

		sanitize.init();

		this.elem.innerHTML = text;
		return this.elem.textContent
			.replace( /"/g, '&quot;' )
			.replace( /'/g, '&#039;' );

	},

};