jQuery Removing specific text from an element

后端 未结 4 824
谎友^
谎友^ 2020-12-02 23:10

I want to remove the text \"By:\" from an element in my website. I want the rest of the text to remain there. How can I achieve that with jQuery? Thank you.

The HTML

相关标签:
4条回答
  • 2020-12-02 23:47

    give an unique id to div, t:

    $('#div_id').html($('#div_id').html().substring(3));
    

    fiddle : http://jsfiddle.net/ChUB4/

    0 讨论(0)
  • 2020-12-02 23:58

    var str = $("#text").text();
    $("#text").text(str.substring(3));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div id="text">By: Anonymous From Minnesota</div>

    Using javascript's substring and give your div an ID to access it easily:

    html:

    <div id="text">By: Anonymous From Minnesota</div>
    

    jquery:

    var str = $("#text").text();
    $("#text").text(str.substring(3));
    

    You could do it in one line too:

    $("#text").text($("#text").text().substring(3));
    
    0 讨论(0)
  • 2020-12-02 23:59

    a more global solution using regular expressions. This will replace By: even if your string structure will change.

    var str = $('div').text().replace(/By:/g, '');
    $('div').text(str);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div id="text">By: Anonymous From Minnesota</div>

    0 讨论(0)
  • 2020-12-03 00:12

    If you wanted to find every element with "By:" in it and remove it, you could try this:

    $(':contains("By:")').each(function(){
        $(this).html($(this).html().split("By:").join(""));
    });
    

    This removes any occurrence of "By:" in any element. If you want to target specfic type of elements, simply change $(':contains("By:")') to include whatever selector suits you.

    0 讨论(0)
提交回复
热议问题