我有一个句子/H1,我需要将其拆分,使其如下所示
原始状态
<h1>This is the heading </h1>
后
<h1>This <br>
is <br>
the <br>
heading </h1>
我有一个句子/H1,我需要将其拆分,使其如下所示
原始状态
<h1>This is the heading </h1>
后
<h1>This <br>
is <br>
the <br>
heading </h1>
我建议:
$('h1').each(
function(){
var that = $(this),
newText = that.text().replace(/\W/g,'<br />');
that.html(newText);
});
参考:
$("h1").html( $("h1").text().replace(/ /g,"<br>"))
$('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/>')+' ');
});
试试这个:
var h = $('h1').text().split(' ').join('<br>');
$('h1').html(h);