2011-08-16 28 views
5

Me preguntaba si hay una forma de seleccionar la última palabra en una DIV. No creo que exista una forma obvia de hacerlo, ¿hay alguna solución alternativa?Seleccionar la última palabra en un contenedor

No me importa usar CSS o Javascript para lograr esto.

Gracias de antemano

Respuesta

2

Prueba esto:

var $div = $('div');  
$div.html($div.text().replace(/(\w+?)$/, '<span>$1</span>')); 

Here is a demo

Si el texto dentro del div no contiene ningún elemento div, entonces esto funcionará. De lo contrario, no lo hará, porque reemplazará todos los elementos anteriores por texto sin formato.

+0

funcionó perfectamente, pero si tenemos algunos signos diacríticos, no se aplica, ¿por qué? ¿algunas ideas? –

0

Probablemente se podría usar Javascript y HTML DOM para acceder al contenido del div y luego simplemente dividir la cadena (con un espacio como separador) y tomar la última parte dividida.

3

<div> o no <div>, se reduce a la manipulación básica de cadenas (utilizando el método match()).

var words = $('#your_div').text().match(/(\w+)/g); 
if (words.length) { 
    var last_word = words[words.length - 1]; 
} 

Construimos un conjunto de todas las palabras que utilizan el método match(), y luego obtener el último (var last_word = words[words.length - 1];), pero sólo si se encontraron algunas palabras (if (words.length)).

+1

gracias por su respuesta, pero no puedo ver cómo se puede utilizar esto como un selector. Necesito ajustar la última palabra en un ''. Tal vez usar el método '.replace()'? –

0

aquí está mi solución a esta pregunta:

Demostración:http://wecodesign.com/demos/stackoverflow-7075397.htm

function getLastWord(words) { 
    lastWord = words.split(' ').pop(); 
    return lastWord; 
} 

$(document).ready(function() { 
    theWords = $('#theWords').html(); 
    lastWord = getLastWord(theWords); 
    $('#lastWord').html(lastWord); 
}); 

arrastramiento del alcance! Teniendo en cuenta los nuevos requisitos para inyectar dinámicamente la etiqueta span, he modificado el código de la siguiente manera (también he actualizado mi demo):

$(document).ready(function() { 
    theWords = $('#theWords').html(); 
    lastWord = getLastWord(theWords); 
    appendCon = '#lastWord'; 
    $(appendCon) .append($('<span> '+lastWord+'</span>')); 
}); 
+0

el problema con esto es que necesito '' para agregarse automáticamente. El contenido se agregará dinámicamente por Wordpress. –

1

Si después de otra solución basada en la expresión regular, usted podría tratar (utiliza jQuery):

$(function() { 
    $('div').each(function() { 
     var $div = $(this); 
     var text = $div.text(); // get the text of everything inside the div 
     // the next line gets the last word followed only by non-word characters in that text 
     // NB: the [\s\S] trick is to match any character, *including* new lines 
     var last_word = $.trim(text).replace(/^[\s\S]*\b(\w+)\b[\W]*$/i, '$1'); 

     // this is from a jsFiddle I tried to post to test it. 
     $('#output').append($div.attr('id') + ': Last word = ' + last_word + '<br />'); 
    }); 
}); 
0

Esto funciona.

var text = 'Lorem Ipsum Dolor Sit Amet'; 
var textSplit = text.split(' ');//split the text with space characters 
var lastPart = textSplit.pop(); // retrieve the last word from the string 
var firstPart = textSplit.join(' '); // retriece the words except the last word 
var result = firstPart + '&nbsp;<strong>' + lastPart + '</strong>'; //join first part and last part and put the required html for the last word 
Cuestiones relacionadas