javascript 从字符串中删除最后一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13647360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:22:05  来源:igfitidea点击:

Remove last line from string

javascriptjquery

提问by user1534664

How do I remove the last line "\n" from a string, if I dont know how big the string will be?

如果我不知道字符串有多大,如何从字符串中删除最后一行“\n”?

var tempHTML = content.document.body.innerHTML;
var HTMLWithoutLastLine = RemoveLastLine(tempHTML);

function RemoveLastLine(tempHTML)
{
   // code
} 

回答by rekire

Try:

尝试:

if(x.lastIndexOf("\n")>0) {
    return x.substring(0, x.lastIndexOf("\n"));
} else {
    return x;
}

回答by Julien Royer

You can use a regular expression (to be tuned depending on what you mean by "last line"):

您可以使用正则表达式(根据“最后一行”的含义进行调整):

return x.replace(/\r?\n?[^\r\n]*$/, "");

回答by Marco Roy

A regex will do it. Here's the simplest one:

正则表达式会做到这一点。这是最简单的一种:

string.replace(/\n.*$/, '')

See regex101 for how it works

请参阅 regex101 了解其工作原理

\nmatches the last line break in the string

\n匹配字符串中的最后一个换行符

.*matches any character, between zero and unlimited times (except for line terminators). So this works whether or not there is content on the last line

.*匹配零次和无限次之间的任何字符(行终止符除外)。所以无论最后一行是否有内容,这都有效

$to match the end of the string

$匹配字符串的结尾

回答by Ivo

In your specific case the function could indeed look like:

在您的特定情况下,该功能确实看起来像:

function(s){
  return i = s.lastIndexOf("\n")
    , s.substring(0, i)
}

Though probably you dont want to have spaces at the end either; in this case a simple replace might work well:

尽管您可能也不希望末尾有空格;在这种情况下,简单的替换可能效果很好:

s.replace(/s+$/, '')

Keep in mind however that new versions of Javascript (ES6+) offer shorthand ways of doing this with built-in prototype functions (trim, trimLeft, trimRight)

但是请记住,新版本的 Javascript ( ES6+) 提供了使用内置原型函数(trimtrimLefttrimRight)执行此操作的速记方法

s.trimRight()

Cheers!

干杯!