Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there an algorithm/library for taking any html document, finding all the 'words' (single words) in the document and the wrapping each word inside a span (or any other html element). I am using angularJS framework which has some jQuery restrictions. Still, even with jQuery i cannot seem to get it to work. I used the .contents().filter().wrap() mechanism outlined on the jQuery documentation. However it is only useful when I want to wrap entire lines of text rather than the individual words. This problem is very frustrating and I would truly appreciate some help. Thanks much!

Okay sorry for the lack of details previously.

My application pulls a string from a database. The string is contains html. I created a custom directive named 'spanner' and bound this directive to the html string on the scope like so:

Inside my directive I try to add a span around each word in the html like so:

.directive('spanner', function($compile){
var linkFn = function(scope, element, attributes)
{
    element.append(scope.spanner);
    angular.forEach(element.find('*').contents(), function(val, key){
        var a = angular.element(val);
        var text;
        if(a.context.nodeType === 3)
        {
            text = a.text();
            text = text.split(' ');
            angular.forEach(text, function(val, key){
                if(key%2 === 0){
                    val = "<span class='even'>" + val + "</span>";
                }
                else
                {
                    val = "<span ng-class='odd'>" + val + "</span>";
                }
                text[key] = val;
            });

            text = text.join(' ');              
        }
        a.html(text);
        element.find('*').contents()[key] = a;            
    });
    $compile(element.contents())(scope);
};

return {
    scope: {
        spanner: '='
    },
    restrict: 'A',
    link: linkFn
};

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this script: JSFiddle

var text = $.trim($('p').text()),
    word = text.split(' '),
    str = "";
$.each( word, function( key, value ) {
  if(key != 0) { str += " "; }
  str += "<span>" + value + "</span>";
});
$('p').html(str);

The big question that remains is how are you going to handle punctuation? -- I'll leave that to you to figure out


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...