Wrap Each Word In An Html Element
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 eleme
Solution 1:
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
Solution 2:
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope){
var str = "How are you doing today?";
var res = str.split(" ");
angular.forEach(res, function(word){
word = "<span>" + word + "<span>";
console.log(word);
});
});
Solution 3:
assuming you are using jQuery in angular and this is done in a directive can do something like:
link: function( scope, elem, attrs){
elem.html(function( _, original){
var words = original.split(' ');
return'<span class="wrap">' + words.join('</span><span class="wrap">') +'</span>';
});
}
Also assumes element contains only text
Post a Comment for "Wrap Each Word In An Html Element"