Galera, vou passar rápido pra postar esta função que recupera e substitui um texto selecionado em um objeto (textarea ou input).
O primeiro parâmetro é o objeto (String com id ou objeto DOM) aonde você quer manipular o texto selecionado, o segundo um booleano, que define se o método para substituir o texto do objeto retornado somente adicionará o texto caso não haja seleção. A função retorna um objeto simples com uma propriedade text que contem a String com o texto selecionado e o método setText() que aceita um parametro que é o texto a ser colocado no lugar do texto selecionado. Abaixo a função:
function selection(obj, set_text_default){
/* @author Bernardo Rufino
* @license Creative Commons Developing Nations: http://creativecommons.org/licenses/devnations/2.0/
* @description Function to manipulate the actual selection
* @returns It returns an object with an attribute *text* with the current selection text and
* a method *setText()* that receives one argument, the text to be set in the selection.
* @parameters The first is the object where you want the selection (DOM or String with id), and
* the second (optional), a boolean, if is true then the *setText()* method will
* append the text if there's no way to replace the selection.
*
* !Nao retire essas informacoes!
* !Do not drop this information!
*/
if(obj.constructor == String){obj = document.getElementById(obj);}
var set_text = (set_text_default) ? function(text){obj.value += text;} : function(){return false;};
var selection = {text: "", setText: set_text};
if(document.selection){
var range = document.selection.createRange();
if(range.text){
selection.text = range.text;
selection.setText = function(text){
range.text = text.replace(/\r?\n/g, "\r\n");
}
}
} else if(typeof(obj.selectionStart) != "undefined"){
selection.text = obj.value.substring(obj.selectionStart, obj.selectionEnd);
selection.setText = function(text){
obj.value = obj.value.substring(0, obj.selectionStart) + text + obj.value.substring(obj.selectionEnd);
}
} else if(window.getSelection){
selection.text = window.getSelection().toString();
}
return selection;
}
Exemplo abaixo usado muito em editores de fóruns para inserir tags BBCode:
var selected = selection("text", true); //Objeto input ou textarea com id "text"
selected.setText("[b]" + selected.text + "[/b]");
Dê uma olhada no exemplo com tags.
Falows pessoal!

Agosto, 27 - 2007 às 9:01 am |
Muito bom bernardo. vou usar isso aí hehehe.
Junho, 12 - 2009 às 3:42 pm |
Muito bom, parabens, isso é demias, melhor beixe assado na bras, rsrs
Junho, 12 - 2009 às 3:45 pm |
Bernado, mais uma coisa, cara, seria muito bom se seu código retirasse a formatação no caso de o usuário selecionar o texto com a tag e clicar sobre o botão novamnte, assim ficaria simples formatar e limpar a formatação.
Mas é muito bom seu código, vou usar isso, rsrsr
Junho, 13 - 2009 às 1:56 pm |
Olá Bernardo, fiz uma alteração na sua função, veja:
function wrapText(obj, before, after){
var selected = selection(obj, true);
/* VERIFICA SE EXISTE TAG NO TEXTO SELECIONADO */
var regex = /]*>(.*)]>/;
if(regex.test(selected.text)){
// RETIRA AS TAGS
var retorno = selected.text.replace(/^(]*>)(.*)(]>)$/, “$2″);
selected.setText(retorno);
}else{
// FORMATA O TEXTO IGUAL ESTAVA ANTES
selected.setText(before + selected.text + after);
}
}
Eu estava tentanto modificar para quando o usuário fosse tentar colocar um texto em negrito que já estava em negrito a formatação fosse removida.
A função acima esta fazendo isso parcialmente, pois se eu tentar colocar um texto em italico por exemplo e esse texto já estiver com alguma formatação ao inves de acrescentar o italico o código esta é removendo o negrito que eu não tinha a intenção de remover.
Você pode me da uma ajuda?