Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the string based on <br/> tag using jquery

How can i split the string containing <br/> tag using jquery. I tried the following code but it get error in console. I am not sure how to split the string based on <br/> tag Here is the code what i tried

jQuery(document).ready(function($)
    {
        var lines = jQuery('this is for testing <br/> How are you<br/>').split('<br/>');
        jQuery.each(lines, function() {
            alert(this);
        });
    });

Any suggestion would be great.

like image 786
Vignesh Pichamani Avatar asked Sep 03 '13 12:09

Vignesh Pichamani


People also ask

How use split method in jquery?

var data = $('#date'). text(); var arr = data. split('/'); $("#date"). html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);

How do you split a string in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

How can I split a string into two JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

Lots of duplicate answers here. This one is different. If you can guarantee the spelling of the <br/> tag, the other answers are fine. But if you have no control over the HTML, the line break tag could come in different formats:

<br/>
<BR/>
<br />
<br>
<br >
...etc.

major browsers can all handle all of these, but only the first will be handled by the suggested .split("<br/>") operation. A more robust option is to use a regular expression to match the tag:

jQuery(document).ready(function($)
{
    var brExp = /<br\s*\/?>/i;
    var lines = ("this is for testing <br/> How are you<BR />").split(brExp);
});

I've written the expression to be case-insensitive, allow any number of spaces after '<br', and the '/' is optional.

like image 167
xr280xr Avatar answered Oct 01 '22 18:10

xr280xr