Javascript 如何从字符串中删除所有换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10805125/
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-08-24 03:00:58  来源:igfitidea点击:

How to remove all line breaks from a string

javascriptregexstring

提问by Wingblade

I have a text in a textarea and I read it out using the .value attribute.

我在 textarea 中有一个文本,我使用 .value 属性读出它。

Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?

现在,我想Enter使用 .replace 和正则表达式从我的文本中删除所有换行符(按 时产生的字符),但是如何在正则表达式中指示换行符?

If that is not possible, is there another way?

如果这是不可能的,还有其他方法吗?

回答by Eremite

How you'd find a line break varies between operating system encodings. Windows would be \r\n, but Linux just uses \nand Apple uses \r.

您如何找到换行符因操作系统编码而异。Windows 会是\r\n,但 Linux 只是使用\n而 Apple 使用\r

I found this in JavaScript line breaks:

我在JavaScript 换行符中发现了这一点:

someText = someText.replace(/(\r\n|\n|\r)/gm, "");

That should remove all kinds of line breaks.

这应该删除各种换行符。

回答by PointedEars

This is probably a FAQ. Anyhow, line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothingto do with character encoding.)

这可能是一个常见问题。无论如何,换行符(更好:换行符)可以是回车符(CR, \r, 在较旧的 Mac 上)、换行符(LF, \n, 在 Unices 包括 Linux 上)或 CR 后跟 LF(\r\n在 WinDOS 上)之一。(与另一个答案相反,这与字符编码无关。)

Therefore, the most efficient RegExpliteral to match all variants is

因此,RegExp匹配所有变体的最有效文字是

/\r?\n|\r/

If you want to match all newlines in a string, use a global match,

如果要匹配字符串中的所有换行符,请使用全局匹配,

/\r?\n|\r/g

respectively. Then proceed with the replacemethod as suggested in several other answers. (Probably you do notwant to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)

分别。然后replace按照其他几个答案中的建议继续使用该方法。(也许你并不想删除换行符,但与其他空格替换它们,例如空格字符,这样的话保持不变。)

回答by RobW

var str = " \n this is a string \n \n \n"

console.log(str);
console.log(str.trim());

String.trim()removes whitespace from the beginning and end of strings... including newlines.

String.trim()从字符串的开头和结尾删除空格......包括换行符。

const myString = "   \n \n\n Hey! \n I'm a string!!!         \n\n";
const trimmedString = myString.trim();

console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"

Here's an example fiddle: http://jsfiddle.net/BLs8u/

这是一个示例小提琴:http: //jsfiddle.net/BLs8u/

NOTE!it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.

笔记!它只修剪字符串的开头和结尾,而不是字符串中间的换行符或空格。

回答by Kendall Frey

You can use \nin a regex for newlines, and \rfor carriage returns.

您可以\n在正则表达式中使用换行符和\r回车符。

var str2 = str.replace(/\n|\r/g, "");

Different operating systems use different line endings, with varying mixtures of \nand \r. This regex will replace them all.

不同的操作系统使用不同的行结尾,具有变化的混合物\n\r。这个正则表达式将全部替换它们。

回答by masi

If you want to remove all control characters, including CR and LF, you can use this:

如果要删除所有控制字符,包括 CR 和 LF,可以使用以下命令:

myString.replace(/[^\x20-\x7E]/gmi, "")

It will remove all non-printable characters. This areall characters NOTwithin the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.

它将删除所有不可打印的字符。这是所有字符不是内的ASCII HEX空间0x20-0x7E。根据需要随意修改 HEX 范围。

回答by Freezystem

The simplest solution would be:

最简单的解决方案是:

let str = '\t\n\r this  \n \t   \r  is \r a   \n test \t  \r \n';
str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"

.replace()with /\s+/gregexp is changing all groupsof white-spaces characters to a single space in the whole string then we .trim()the result to remove all exceeding white-spaces before and after the text.

.replace()使用正则/\s+/g表达式将所有空格字符更改为整个字符串中的单个空格,然后我们.trim()将删除文本前后所有超出的空格。

Are considered as white-spaces characters:
[ \f\n\r\t\v?\u00a0\u1680?\u2000?-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

被视为空格字符:
[ \f\n\r\t\v?\u00a0\u1680?\u2000?-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

回答by Si7ius

To remove new line chars use this:

要删除新行字符,请使用以下命令:

yourString.replace(/\r?\n?/g, '')

Then you can trim your string to remove leading and trailing spaces:

然后,您可以修剪字符串以删除前导和尾随空格:

yourString.trim()

回答by Gordon Freeman

var str = "bar\r\nbaz\nfoo";

str.replace(/[\r\n]/g, '');

>> "barbazfoo"

回答by futz.co

The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

PointedEars 提供的答案是我们大多数人需要的一切。但是按照 Mathias Bynens 的回答,我进行了一次维基百科之旅,发现了这个:https://en.wikipedia.org/wiki/Newline 。

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

以下是一个插入函数,它实现了上述 Wiki 页面在此答案时认为“新行”的所有内容。

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

如果某些东西不适合您的情况,只需将其删除即可。此外,如果您正在寻找性能,这可能不是它,但对于在任何情况下都能完成工作的快速工具,这应该很有用。

// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});

回答by chaya D

I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:

我正在添加我的答案,它只是上面的一个插件,对于我来说,我尝试了所有 /n 选项但它没有用,我看到我的文本来自带有双斜杠的服务器,所以我使用了这个:

var fixedText = yourString.replace(/(\r\n|\n|\r|\n)/gm, '');