javascript - Split array by tag and delete all similar element -
i have html page text , need output inner html tag b alphabetical order in lower case. i'm begginer, don't strict.
my code here (text example): http://jsfiddle.net/pamjaranka/ebeptlzj/1/
now want to: 1) save upper case inner html tag abbr; 2) delete similar element array (as mabs).
i trying find way split array tag, i've done is:
for(var i=0; i<allbold.length; i++){ labels[i] = allbold[i].innerhtml; } var searchterm = ['abbr']; var abbr = []; var keywordindex; $.each(labels, function(i) { $.each(searchterm, function(j) { var rsearchterm = new regexp('\\b' + searchterm[j] + '\\b','i'); if (labels[i].match(rsearchterm)) { keywordindex = i; for(var j=0; j<labels.length; j++){ abbr[i] = labels[i]; } } }); });
vanilla js solution (no library required, see jsfiddle):
var allbold = document.queryselectorall("b"), words = document.queryselector("#words"), labels = {}, i, word, keys, label; // first, collect words in object (this eliminates duplicates) for(i = 0; < allbold.length; i++) { word = allbold[i].textcontent.trim(); if (word === 'labels:') continue; labels[word.tolowercase()] = word; } // sort object keys , output words in original case keys = object.keys(labels).sort(); for(i = 0; < keys.length; i++){ label = document.createtextnode("span"); label.textcontent = labels[keys[i]]; words.appendchild(label); // add comma if necessary if (i < keys.length - 1) { words.appendchild(document.createtextnode(", ")); } }
with 1 helper:
string.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ""); };
jquery solution (see jsfiddle):
$(".content b").map(function () { return $("<span>", {text: $.trim(this.textcontent)})[0]; }).unique(function () { return lcasetext(this); }).sort(function (a, b) { return lcasetext(a) < lcasetext(b) ? -1 : 1; }).appendto("#words");
with 2 helpers:
$.fn.extend({ unique: function (keyfunc) { var keys = {}; return this.map(function () { var key = keyfunc.apply(this); if (!keys.hasownproperty(key)) { keys[key] = true; return this; } }); } }); function lcasetext(element) { return element.textcontent.tolowercase(); }
Comments
Post a Comment