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

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

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


当前回答

你可以在正则表达式中用\n表示换行,用\r表示回车。

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

不同的操作系统使用不同的行尾,使用不同的\n和\r组合。这个正则表达式将全部替换。

其他回答

最简单的解决方案是:

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

.replace() with /\s+/g regexp将整个字符串中的所有空白字符组更改为单个空格,然后使用.trim()结果删除文本前后所有超出的空白。

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

Var STR = " \n this is a string \n \n \n" console.log (str); console.log (str.trim ());

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!!!"

这里有一个例子:http://jsfiddle.net/BLs8u/

注意!它只修饰字符串的开头和结尾,而不修饰字符串中间的换行符或空格。

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

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

>> "barbazfoo"

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

Const text = 'test\nwith\nline\nbreaks'

const textwithoutbreak = text.split('\n')。加入(' ')