regex to remove last line of block of text
how do i remove the last line from a block of text in java script without using loops.(only using regex) eg.,
"The Internet is a global system of interconnected computer networks that use the standard Internet Protocol Suite (TCP/IP) to serve billions of users wor开发者_如何学Cldwide. It is a network of networks that consists of millions of private and public, academic, business, and government networks&&".
The last line always have "&&".
var str = "The ... and government networks&&";
str.replace(/\.[^.]+&&$/,'.');
If by last line you mean last sentence. And the last sentence doesn't contain a period.
Your text has no newlines in it, so I guess you mean to remove the last sentence-
string.replace(/\.[^\.]+\.?$/,'.');
If you want to be sure not to remove the only sentence, use
string.replace(/(\S+\.)[^\.]+\.?$/,'$1')
You will need to some heavier lifting to avoid cutting off lines that have abbreviations with periods, like Mr. Jones, Dr. Spock, Mrs. Jones and St. Andrew. Like removing their periods before the amputation and replacing them after. (split here for readibility)
string= string.replace(/\b(Mr|Dr|Mrs|St)\. /g,'$1 ')
.replace(/(\S+\.)[^\.]+\.?$/,'$1').replace(/\b(Mr|Dr|Mrs|St) +/g,'$1. ')
if you need the new line has "computer new line"
var str = "he ... and government networks&&";
str.replace(/\n[^\n]*&&$/,'');
Like this?
"First Line\n.sth.&&.\nAnother\nLast Line&&Last Word".replace(/\n.*&&.*$/,'');
Result
First Line
..sth.&&.
Another
According to your question, The last line always have "&&"., it does not mean that must be end with &&, right? and other lines can have && too.
If your text has no line breaks, a "last line" does not exist. It only exists when it is displayed in the browser, but not as part of the text. Although you insist on "only using regex", a regex cannot find it.
You can get away with it if you use a fixed width font
, but that is unlikely. You can also loop until you reach the target height, but this is undesired.
A better approach here it to use CSS. Here's a simplified version that shows the first two lines and hides the rest:
p.TwoLines {
overflow: hidden; /* no scroll bars */
font-size: 10pt; /* here I have a fixed size, for example */
line-height: 1.5;
height: 30pt /* 1.5*2lines *10sizeofline */;
width: 300px; /* not needed, just to see the effect */
}
Preview: http://jsbin.com/ufihe3
精彩评论