Split the string based on
tag using jquery

前端 未结 10 843
温柔的废话
温柔的废话 2021-01-17 20:04

How can i split the string containing
tag using jquery. I tried the following code but it get error in console. I am not sure how to split the strin

相关标签:
10条回答
  • 2021-01-17 20:51

    Here is the Working code

    jQuery(document).ready(function($)
        {
    
            var lines = 'this is for testing <br/> How are you<br/>'.split('<br/>');
                    alert("workig");
            jQuery.each(lines, function() {
                alert(this);
            });
        });
    
    0 讨论(0)
  • 2021-01-17 20:59
    jQuery(document).ready(function($)
    {
    
    var str = 'this is for testing <br/> How are you<br/>';
    var lines = str .split('<br/>');
         jQuery.each(lines, function() {
            alert(this);
        });
    });
    
    0 讨论(0)
  • 2021-01-17 21:00

    No need to wrap in jquery like :

    jQuery('this is for testing <br/> How are you<br/>').split('<br/>');
    
    Can be like :
    
    ('this is for testing <br/> How are you<br/>').split('<br/>');
    

    DEMO

    0 讨论(0)
  • 2021-01-17 21:01

    That's no jQuery solution, but hopefully somebody will find it useful. The function returns one or two elements.

    function splitContentsOnBr(el) {
        const before = document.createElement('div');
        const after = document.createElement('div');
        let found = false;
        el.childNodes.forEach(c => {
            if (found) {
                after.appendChild(c.cloneNode(true));
            } else if (c.tagName == 'BR') {
                found = true;
            } else {
                before.appendChild(c.cloneNode(true));
            }
        });
        return after.childNodes.length ? [before, after] : [before];
    }
    document.querySelector('#result').innerHTML = splitContentsOnBr(document.querySelector('h1'))
        .map(el => el.textContent.trim())
        .join(', ');
    <h1>
      First part
      <br>
      Second part
    </h1>
    <div id="result">
    </div>

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