简体   繁体   English

Javascript 更换增加几<br> 's 到字符串的开头和结尾

[英]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.我正在使用 Javascript 在标签中的每个文本字母之间添加<br /> 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它在字符串的开头和结尾添加了几个额外的<br />标签,而不是将Asia变成

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> .这只是<h1>Asia</h1>

Try trimming your text, as those could be whitespaces:尝试修剪你的文本,因为那些可能是空格:

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

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

You probably have a bunch of leading and trailing whitespace coming back from .text .您可能有一堆从.text返回的前导和尾随空格。 You should strip off the whitespace before inserting your <br> tags:您应该在插入<br>标签之前去掉空格:

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/或者一个活生生的例子: 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()使用正则表达式很容易使您的代码不清楚,所以我用 String.split() 和 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('') );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM