开发者

Javascript Replace adds several <br />'s to beginning and end of string

开发者 https://www.devze.com 2023-03-01 08:15 出处:网络
I\'m using Javascript to add <br /> in between every letter of text in a tag. Code is as follows:

I'm using Javascript to add <br /> in between every letter of text in a tag. Code is as follows:

$(this).html($(this).text().replace(/(.{1})/g, "$1<br />"));

It's adding several extra <br /> tags to the beginning and end of the string, so instead of turning Asia into

A<br />s<br />i<br />a

I end up with

<br /><br /><br /><br /><br /><br /><br /><br />A<br />s<br />i<br />a<br /><br /><br /><br /><br /><br /><br /><br 开发者_JAVA百科/>

Help!

Edit: There are no leading or trailing spaces. It's simply <h1>Asia</h1>.


Rather than using . which matches any character, if you're after letters why not do something like:

$(this).html($(this).text().replace(/(\w{1})/g, "$1<br />"));


Try trimming your text, as those could be whitespaces:

$(this).html(jQuery.trim($(this).text()).replace(/(.{1})/g, "$1<br />"));


You probably have a bunch of leading and trailing whitespace coming back from .text. You should strip off the whitespace before inserting your <br> tags:

var $this = $(this);
var t  = $this.text().replace(/^\s*/, '').replace(/\s*$/, '');
$this.html(t.replace(/(.{1})/g, "$1<br />"));

Or a live example: http://jsfiddle.net/ambiguous/LAH99/


It's easy to make your code unclear with regex so I wrote a version with String.split() and Array.join()

var $this = $(this);
var text = $(this).text();
var arr = text.split('');
for( var i = 0; i < arr.length -1; i++ ) {
    arr[ i ] += '<br />';
}
$this.text( arr.join('') );
0

精彩评论

暂无评论...
验证码 换一张
取 消