rich text editor

facebook

by Paco86

JavaScript

function render2(str, styles) {
	var stack = [];
  var res = '';
	for (var i = 0; i < str.length; i++) {
  	var tags = [];
    
    // get current tags
    styles.forEach(([start, end, tag]) => {
    	if (i >= start && i < end) {
      	tags.push(tag);
      }
    });
    
    // Pop unwanted tags off the stack
    while (stack.some(tag => tags.indexOf(tag) === -1)) {
      res += `</${ stack.pop() }>`;
    }

    // Push wanted tags to the stack
    tags.forEach((tag) => {
    	if (stack.indexOf(tag) === -1) {
        stack.push(tag);
        res += `<${ tag }>`;
      }
    });
    
    
    res += str[i];
    
    // If there are tags to close at the end of the string
    if (i === str.length - 1) {
    	while (stack.length) {
      	res += `</${ stack.pop() }>`;
      }
    }
  }
  
  return res;
}

const res = render2('Hello, world', [[0, 4, 'i'], [1, 3, 'u'], [2, 8, 'b']]);
document.body.innerHTML = res;
console.log(res);