How can I determine the last element in a string using jQuery?

I have this markup here:

<p>
    <?= $d['contact'] ?> | <?= $d['address'] ?>
</p>
<p>
    T: <?= $d['phone'] ?> | 
    <a href="mailto:<?= $d['email'] ?>"><?= $d['email'] ?></a> | 
    <a href="http://<?= $d['website'] ?>" target="_blank"><?= $d['website'] ?></a>
</p>

      

And since this is for flexible layout, I would like to remove the separator |

when it is the last item on the line. Is it possible? I am thinking about wrapping it in <span></span>

and calling it whenever it is the last element.

+3


source to share


2 answers


This can be done by making sure that the content following the separator is an element, and then check the positions of the separator and the next element:

<p>
    <?= $d['contact'] ?><span class="seperator"> | </span><span><?= $d['address'] ?></span>
</p>
<p>
    T: <?= $d['phone'] ?><span class="seperator"> | </span>
    <a href="mailto:<?= $d['email'] ?>"><?= $d['email'] ?></a><span class="seperator"> | </span>
    <a href="http://<?= $d['website'] ?>" target="_blank"><?= $d['website'] ?></a>
</p>

      

$(function () {
    $(window).resize(function () {
        $(".seperator").each(function () {
            var t = $(this);
            // use visibility since it does not free the space
            t.css("visibility", (t.next().offset().top > t.offset().top) ? "hidden" : "visible");
        });
    }).resize();
});

      



Edit : t.next().offset()

must be checked for .length

, otherwise the console will show an error for the last item Uncaught TypeError: Cannot read property 'top' of undefined

(there is no after the last item .next()

). Therefore, the code should look something like this:

$(function () {
        $(window).resize(function () {
            $(".seperator").each(function () {
                var t = $(this);
                var this_offset = t.offset().top;
                if (t.next().length) {
                  var next_offset = t.next().offset().top; 
                }
                // use visibility since it does not free the space
                t.css("visibility", (next_offset > this_offset) ? "hidden" : "visible");
            });
        }).resize();
    });

      

+1


source


This will delete the last | char

function removeReverseCharLike(str,char){
    i = str.lastIndexOf(char);
    if (i != -1) {
        str = str.substr(0,i) + str.substr(i+1,i);
    }
    return str;
}

str = $('p:last').html();
removeReverseCharLike(str,char);

      



if you want to trim the last '|' char, if it is the last char in the sentence, you have to split the html string

strArr = $('#test').html().split('\n')
var html = '';
for(i in strArr){
  html += strArr[i].replace(/\|$/, '');
}

      

0


source







All Articles