最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove blank lines in div - Stack Overflow

programmeradmin7浏览0评论

I have a tag:

<pre>
     this is a

    this is b


       this is c
</pre>

After parsed by browser, it outputs:

     this is a

    this is b


       this is c

What I want is:

this is a
this is b
this is c

Is there any way to only use client methods to do this?

Change <pre> tag to <div>? But it turns to single line, not I want.

Add css? I did not find a style to achieve.

Or use javascript?

PS: the content in <pre> tag is generated by liquid template {{ post.content}} , it is immutable.

I have a tag:

<pre>
     this is a

    this is b


       this is c
</pre>

After parsed by browser, it outputs:

     this is a

    this is b


       this is c

What I want is:

this is a
this is b
this is c

Is there any way to only use client methods to do this?

Change <pre> tag to <div>? But it turns to single line, not I want.

Add css? I did not find a style to achieve.

Or use javascript?

PS: the content in <pre> tag is generated by liquid template {{ post.content}} , it is immutable.

Share Improve this question edited Feb 18, 2017 at 7:55 kyshel asked Feb 18, 2017 at 7:39 kyshelkyshel 6027 silver badges11 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4

Trim and filter out empty lines.

// get the pre tag
var pre = document.querySelector('pre');

pre.innerHTML = pre.innerHTML
  // split by new line
  .split('\n')
  // iterate and trim out
  .map(function(v) {
    return v.trim()
    // filter out non-empty string
  }).filter(function(v) {
    return v != '';
    // join using newline char
  }).join('\n')
<pre>
     this is a

    this is b


       this is c
</pre>

You are using pre tag which mean preformatted text, anything included between this tag whether it's space or line-break, the output will be same as included.

The HTML element represents preformatted text. Text within this element is typically displayed in a non-proportional ("monospace") font exactly as it is laid out in the file. Whitespace inside this element is displayed as typed.

So you could make use of some other tag, still you could remove space between those sentences using JavaScript as added by Pranav C Balan

<pre>
  
  Hi xyz demo text.Hi xyz demo text.
  
          Hi xyz demo text.
  
  Hi xyz demo text. 
</pre>

dont use "pre" tag. use simple

<div>this is a</div>
<div>this is b</div>
<div>this is c</div>

i hope this helps

<p>
 this is a<br/>
 this is b<br/>
 this is c<br/>
</p>

with HTML, you can do this! Pre tag in HTML prints as it is without a word-wrap and with whitespace in tact.

发布评论

评论列表(0)

  1. 暂无评论