2011-05-12 18 views
5

¿Existe un método sencillo para buscar dentro de un div para una cadena específica y reemplazarla por otra? No puedo usar .replaceWith solo porque hay otros elementos dentro del div que necesito preservar. He intentado varios métodos de JavaScript encontrados aquí en vano.Búsqueda y reemplazo de JavaScript simple

Así que algo como:

$('#foo').find('this string').replaceWith('this other string'); 

para:

<div id="foo"><div id="child">Other Element</div>this string</div> 

Gracias.

+0

ver http://stackoverflow.com/questions/2349138/jquery-find-and-replace-text-without-element-id/2349208#2349208 – Anurag

Respuesta

6

Prueba esto:

var foo = $('#foo').html(); 

foo = foo.replace('this string', 'this other string'); 

$('#foo').html(foo); 

violín: http://jsfiddle.net/maniator/w9GzF/

+0

"hay otros elementos dentro del div que necesito preservar" - esto no sería adecuado –

+0

@Gary, ¿por qué no? – Neal

+1

Esto no funciona si tiene varias apariciones de 'esta cadena'. –

1

¿Qué pasa con String.replace();?

p. Ej.

$("#div").html($("#div").html().replace("search string", "replace string")); 

O explosionada:

var $divElement = $("#div");   //Find the div to perform replace on 
var divContent = $divElement.html(); //Get the div's content 
divContent = divContent.replace("search string", "replace string"); //Perform replace 
$divElement.html(divContent);  //Replace contents of div element. 
+0

Nada. Eso también funciona ¡Gracias! – pac

8

Esto reemplaza todas las ocurrencias:

var $foo = $('#foo'), 
    fooHtml = $foo.html(); 

$foo.html(fooHtml.replace(/this string/g, 'this other string')); 
+0

hehehehe :-p funny – Neal

+0

¿qué es? mi respuesta o los comentarios sobre tu respuesta? –

+0

wha? ¿por qué este obtiene '+ 2'? lol – Neal

2

Aquí hay un plugin jQuery que acabo de escribir que proporciona safeReplace para colecciones.

(function($){ 

$.fn.safeReplace = function (find, replacement) { 

    return this.each(function(index, elem) { 

     var 
      queue = [elem], 
      node, 
      i; 

     while (queue.length) { 

      node = queue.shift(); 

      if (node.nodeType === 1) { 
       i = node.childNodes.length; 
       while (i--) { 
        queue[queue.length] = node.childNodes[i]; 
       } 
      } else if (node.nodeType === 3) { 
       node.nodeValue = node.nodeValue.replace(find, replacement); 
      } 
     } 

    }); 
}; 

})(jQuery); 

Y aquí es cómo lo usa:

$('#foo').safeReplace(/this string/g, 'something else'); 

sólo lo he probado en FF 4, y sólo en la entrada de la muestra HTML - Se recomienda realizar más pruebas.

Espero que esto ayude!

0

Esta funciona todas las veces que aparece el término, y no matará a cualquiera de las cosas importantes que no se debe cambiar (almacenados en la matriz excluye).

uso:. findAndReplace('dog','cat', document.getElementById('content'));

/* js find andreplace Based on http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ */ 

function findAndReplace(searchText, replacement, searchNode) { 
if (!searchText || typeof replacement === 'undefined') { 
    return; 
} 
var regex = typeof searchText === 'string' ? 
      new RegExp(searchText, 'g') : searchText, 
    childNodes = (searchNode || document.body).childNodes, 
    cnLength = childNodes.length, 
    excludes = ['html','head','style','link','meta','script','object','iframe']; 
while (cnLength--) { 
    var currentNode = childNodes[cnLength]; 
    if (currentNode.nodeType === 1 && 
     excludes.indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) { 
     arguments.callee(searchText, replacement, currentNode); 
    } 
    if (currentNode.nodeType !== 3 || !regex.test(currentNode.data)) { 
     continue; 
    } 
    var parent = currentNode.parentNode, 
     frag = (function(){ 
      var html = currentNode.data.replace(regex, replacement), 
       wrap = document.createElement('div'), 
       frag = document.createDocumentFragment(); 
      wrap.innerHTML = html; 
      while (wrap.firstChild) { 
       frag.appendChild(wrap.firstChild); 
      } 
      return frag; 
     })(); 
    parent.insertBefore(frag, currentNode); 
    parent.removeChild(currentNode); 
} 
} 
3

Simplemente usando html() replace() con el partido todo atributo resultados elemento o etiqueta con su nombre.

Me enfrento a este problema también, mi solución es similar a la función findAndReplace() desde http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ pero usando la expresión regular para obtener todo el textNode y buscar en cada uno de ellos.

function epubSearch(query) { 
    var d = document.getElementsByTagName("body")[0]; 
    var re = new RegExp(query, "gi");//pattern for keyword 
    var re0 = new RegExp("[>][^><]*[><]", "gi");//pattern to get textnode 

    d.innerHTML = d.innerHTML.replace(re0, function (text) { 
     // with each textNode, looking for keyword 
     return text.replace(re, "<span class=\"search-result\" style=\"background-color:red;\">$&</span>"); 
    }); 
} 
Cuestiones relacionadas