Обернуть текст в список (bbcode)


наша форма с кнопками и текстом

<form action="" method="POST">
<button type="button" onclick="wrapText('edit','[list]','[/list]');">LI</button>
<button type="button" onclick="wrapText('edit','[ol=1]','[/ol]');">OL</button><br>
<textarea id="edit" name="message" rows="10" cols="50">
This is some example text.
This is some example text.
This is some example text.
This is some example text.
</textarea>
</form>

и функция обертки

<script>
function wrapText(elementID, openTag, closeTag) {
    var textArea = document.getElementById(elementID);

    if (typeof(textArea.selectionStart) != "undefined") {
        var begin = textArea.value.substr(0, textArea.selectionStart);
        var selection = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart);
        var end = textArea.value.substr(textArea.selectionEnd);
		
		var stringArray = selection.split('\n');
		for (var i = 0; i < stringArray.length; i++) {
			stringArray[i] = '[*] '+stringArray[i];
		}
		selection = stringArray.join('\n');
		//console.log(selection);
        textArea.value = begin + openTag + '\n' + selection + '\n' + closeTag + end;
    }
}
</script>

пример работы тут