Chris Patten
Chris Patten

Reputation: 129

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

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 />

Help!

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

Upvotes: 0

Views: 334

Answers (4)

generalhenry
generalhenry

Reputation: 17319

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('') );

Upvotes: 0

mu is too short
mu is too short

Reputation: 434785

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/

Upvotes: 0

Town
Town

Reputation: 14906

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 />"));

Upvotes: 3

Blender
Blender

Reputation: 298402

Try trimming your text, as those could be whitespaces:

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

Upvotes: 3

Related Questions