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

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

如果不可能,还有别的办法吗?


当前回答

regex中的换行符是\n,因此您的脚本将是

var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));

其他回答

这将用空格替换换行符。

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

阅读这篇文章。

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

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

然后你可以删除字符串的前导和尾随空格:

yourString.trim()

如果你想删除所有的控制字符,包括CR和LF,你可以使用这个:

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

它将删除所有不可打印的字符。这些字符都不在ASCII十六进制空间0x20-0x7E内。请根据需要随意修改HEX范围。

换行符(最好是换行符)可以是回车符(CR, \r,在旧的mac上),换行符(LF, \n,在unix包括Linux上)或CR后面跟着LF (\r\n,在windows上)。(与另一个答案相反,这与字符编码无关。)

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

/\r?\n|\r/

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

/\r?\n|\r/g

分别。然后按照其他几个答案中建议的替换方法进行。(可能您不希望删除换行符,而是使用其他空白符替换它们,例如空格字符,以便单词保持完整。)

PointedEars提供的答案是我们大多数人需要的一切。但根据马赛厄斯·拜恩斯的回答,我在维基百科上找到了这个:https://en.wikipedia.org/wiki/Newline。

下面是一个下拉函数,它实现了上面Wiki页面在回答这个问题时考虑的所有“新行”。

如果有什么东西不适合你的箱子,就把它拿掉。此外,如果您正在寻找性能,这可能不是它,但对于一个快速的工具,在任何情况下完成工作,这应该是有用的。

// 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`)
});