简体   繁体   中英

Line wrap string

I have a string sent back from the github api module that is formatted exactly like this:

Added debug mode for developers

Simply add the class DEBUG to the body and you'll notice little boxes
scattered throughout your site attached to each grid item.

I'm wondering if there's a css option to clear these lines as the browsers reads the above like this:

Added debug mode for developers Simply add the class DEBUG to the body and you'll notice little boxes
scattered throughout your site attached to each grid item.

I didn't really want to split the string apart with javacsript but if I have to I guess I will :)

I've tried word-break:break-word; however this just splits lines for longer strings with no spaces. I've also tried white-space: nowrap; however this literally just doesn't wrap.

If I console log the data, chrome has two characters after the word 'developers' which is what is causing the line breaks, are these selectable by javascript?

Any help would be great!

Your question is a little unclear, but I'm assuming you want to keep the line breaks that are included in the string - rather than the browser default of ignoring them completely.

You'll want one of the pre options for the white-space property.

/* Display text exactly as entered */
white-space: pre;

/* Display as entered, plus extra linebreaks as needed for long lines */
white-space: pre-wrap;

/* Display newlines as entered, plus extra linebreaks as needed for long lines */
white-space: pre-line;

Some notes about the differences:

  1. pre is the equivalent of wrapping the whole thing in a <pre> tag.

  2. The difference between pre and pre-wrap is whether extra linebreaks will be added as needed for long lines.

  3. The difference between pre-wrap and pre-line is whether all whitespace is preserved (including spaces), or only newlines.

  4. pre-line is the equivilant of replacing all newlines with <br> tags.

You can see a comparison of the different styles here: http://jsfiddle.net/Gcexh/


The other problem you will encounter is that you've got a linebreak between the last 2 lines of your input when you probably don't necessarily want a linebreak there.

You can fix that by dropping any single-newlines, and only keeping around the double-newlines like the ones that separate the first two lines.

This would ideally be done on the server side, but can also be done in javascript like this:
(with thanks to @JanDvorak):

text = text.replace(/(\n\s*\n)|\n/g, "$1 ")

I don't think there is a way to do it with css. The javascript way:

var myStr = "Your multiline\n\nstring...";
for (;;)
{
     if (myStr.indexOf("\n") != -1)
          myStr = myStr.replace("\n", " ");
     else
          break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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