Pull to refresh

Замена прямых кавычек на «ёлочки» на javascript

Долго искал готовое решение для замены в вводимом тексте одинарных и двойных прямых кавычек на «ёлочки», не нашел. Написал свое. Решение достаточно простое и, думаю, многим пригодится.

Функции передается текст из какого-либо визуального редактора, в виде html.
Кавычки заменяются только в тексте (параметры тегов не затрагиваются), вложенность тегов значения не имеет.

Функция:
function changeQuotes(text){
	var el = document.createElement("DIV");
	el.innerHTML = text;
	for(var i=0, l=el.childNodes.length; i<l; i++){
		if (el.childNodes[i].hasChildNodes() && el.childNodes.length>1){
			el.childNodes[i].innerHTML = changeQuotes(el.childNodes[i].innerHTML);
		}
		else{
			el.childNodes[i].textContent = el.childNodes[i].textContent.replace(/\x27/g, '\x22').replace(/(\w)\x22(\w)/g, '$1\x27$2').replace(/(^)\x22(\s)/g, '$1»$2').replace(/(^|\s|\()"/g, "$1«").replace(/"(\;|\!|\?|\:|\.|\,|$|\)|\s)/g, "»$1");
		}
	}
	return el.innerHTML;
}



Использование (допустим, что editor — это textarea, с текстом из реактора)
document.getElementById('editor').value = changeQuotes(document.getElementById('editor').value);


P.S. Подобное решение есть здесь: masscode.ru/index.php/k2/item/21-liquotes, но оно выполнено как плагин к jQuery, который используется не всеми.
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.