1

我有一个句子/H1,我需要将其拆分,使其如下所示

原始状态

<h1>This is the heading </h1>

<h1>This <br> 
is <br> 
the <br> 
heading </h1>
4

4 回答 4

3

我建议:

$('h1').each(
    function(){
        var that = $(this),
            newText = that.text().replace(/\W/g,'<br />');
        that.html(newText);
    });

参考:

于 2012-05-13T15:14:44.470 回答
2
$("h1").html( $("h1").text().replace(/ /g,"<br>"))​
于 2012-05-13T15:17:56.240 回答
1
$('h1').each(function() {
    var txt = $(this).html().replace(/^\s*(.*?)\s*$/,'$1');
    // this trims the string
    $(this).html(txt.split(/\s+/).join(' <br/>')+' ');
    // this splits the character groups (not containing spaces)
    // and joins them by a br tag, then adds an extra space at the end.
});

替代方案和更短的版本(感谢VisioN):

$('h1').each(function() {
    $(this).html($.trim($(this).html()).split(/\s+/).join(' <br/>')+' ');
});
于 2012-05-13T15:24:34.870 回答
0

试试这个:

var h = $('h1').text().split(' ').join('<br>'); 
$('h1').html(h);
于 2012-05-13T15:25:03.827 回答