-2

I have written html as below lines of code.

<div class="da-slide">
    <h2><i><asp:Label ID="lblHeading3" runat="server"></asp:Label></i></h2>
    <p>
       <i><asp:Label ID="lblDescription3" runat="server"></asp:Label> </i>
    </p>
    <div class="da-img">
       <img src="../img/bg/html5andcss3.png" alt="image01" />
    </div>
</div>

Now I want to add br tag inside p tag after every four words dynamically. Please help me!!!

blgt
  • 8,135
  • 1
  • 25
  • 28
Nida
  • 1,672
  • 3
  • 35
  • 68

2 Answers2

1

Relying on this answer on how to get all the words of a specific text-node you can try the following:

var res = $('.da-slide p *').contents().map(function () {
    if (this.nodeType == 3 && this.nodeValue.trim() != "") //check for nodetype text and ignore empty text nodes
    return this.nodeValue.trim().split(/\W+/); //split the nodevalue to get words.
}).get(); //get the array of words.

var new_content = [];
$.each(res, function(index, value){
    index++; // avoid the modulo operation with index 0
    if(index % 4 === 0){
        new_content.push(value + '<br/>'); //add a break after every 4th word
    }else{
        new_content.push(value);
    }
    console.log(new_string);

});

$('.da-slide p i').html(new_content.join(' ')); //concatenate the new content with whitespaces

Demo


Reference

.contents()

.map()

.get()

.each()

Node

Community
  • 1
  • 1
empiric
  • 7,825
  • 7
  • 37
  • 48
1

I don't think this is the best approach; however you could achieve this using split, mod and join

// find all <p> elements in the 'da-slide' using jQuery and loop through each instance
$('p', '.da-slide').each(function(p_i, p_el){

    // get the text for this <p> element
    var txt = $(p_el).text();

    // split the text into individual words (assume separated by space)
    var txt_split = txt.split(' ');

    // every 4th word place a <br>
    var txt_tokenized = [];
    txt_split.forEach(function(string, index){
        if (parseInt(index) % 4 == 0){
            txt_tokenized.push('<br/>');
        }
        txt_tokenized.push(string);
    });

    // rebuild as html    
    $(p_el).html(txt_tokenized.join(' '));
});
jasonscript
  • 6,039
  • 3
  • 28
  • 43