javascript - Delete the character that immediately precedes an element -
i have text content capturing third-party source, , contains emoji, represented image elements. find each of emoji image elements, , convert them unicode character emoji using following code:
$(this).find('img.emoji').each(function(i){ emoji = decodeuricomponent($(this).data('textvalue')); $(this).replacewith(emoji); });
however, text preceding each emoji image element contains whitespace character, right before emoji. see:
'[...] blah blah blah <img class="emoji" data-textvalue="%f0%9f%98%92">'
but should be:
'[...] blah blah blah <img class="emoji" data-textvalue="%f0%9f%98%92">'
because coming third-party source, have no control on original copy. but, remove whitespace character in each instance of emoji image (whether before or after converting unicode doesn't matter, suspect may easier before). how accomplish this?
one idea had possibly character location of beginning of image element using javascript's str.indexof
, , delete character 1 less that. require converting parent element string, , cause problems if intial text contained phrase "<img"
, unlikely be.
is there easy way missing?
i'd break out of jquery here , use native javascript - it's better cases you've got tags splashed text that.
the best way think (this browser's internal representation) bits of un-tagged text have special invisible tag around them, instead of
<div>i ice-cream! <img src='ice-cream'></img> it's yummy!</div>
you've got
<div> <textnode>i ice-cream! </textnode> <img src='ice-cream'></img> <textnode> it's yummy!</textnode> </div>
javascript let loop through these different elements, , trim ones before <img>
tags. should work (the get(0)
gets jquery element native javascript one):
var childnodes = $(this).get(0).childnodes; //start @ 1 instead of 0 - first node irrelevant here (var i=1; i<childnodes.length; i++) { var node = childnode[i]; if ( isnodeanimg( node ) ) { var previousnode = childnodes[i-1]; if ( isnodeatextnode() ) { striptrailingspacefrom( previousnode ); } } } function isnodeanimg(node) { return (node.nodetype == node.element_node && node.nodename == "img"); } function isnodeatextnode(node) { previousnode.nodetype == node.text_node } function striptrailingspacefrom( node ) { var text = node.textcontent; var lastcharacter = text.charat( text.length - 1 ); if ( lastcharacter === ' ' ) { node.textcontent = text.substring(0, text.length - 1); } }
Comments
Post a Comment