如何用 javascript 中的空格替换换行符/换行符?

我有一个 var,它包含这种格式的大量单词(数百万) :

var words =  "
car
house
home
computer
go
went
";

我想创建一个函数用空格替换每个单词之间的换行符。

所以结果应该是这样的:

car house home computer go went
126062 次浏览

一些简单的解决方案看起来像

words.replace(/(\n)/g," ");

你可以使用 .replace()函数:

words = words.replace(/\n/g, " ");

请注意,您需要正则表达式上的 g标志来进行替换,以便用空格替换所有换行,而不仅仅是第一行。

Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.

let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");


console.log("After:");
console.log(words);

代码: (FIXED)

var new_words = words.replace(/\n/g," ");

如果有 多个换行符(换行符) ,如果可以同时有 \r\n,你需要 替换所有后续的换行符一个空间,使用

var new_words = words.replace(/[\r\n]+/g," ");

参见 正则表达式演示

要匹配 所有 Unicode 换行符并替换/删除它们,请将 \x0B\x0C\u0085\u2028\u2029添加到上述正则表达式:

/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g

/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g的意思是:

  • [-开始一个正字符类,匹配其中定义的任何单个字符:
    • \r - (\x0D) - \n] - a carriage return (CR)
    • \n-(\x0A)-换行符(LF)
    • 线性制表(LT)
    • \x0C型馈电(FF)
    • \u0085-下一行(NEL)
    • 线路分离器(LS)
    • 段落分隔符(PS)
  • 字符类的结尾
  • +-使正则表达式引擎与前一个原子(这里的字符类)匹配一次或多次的量词(匹配连续的换行符)
  • /g-查找并替换提供的字符串中的所有匹配项。

var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";

不需要全局正则表达式,使用 replaceAll代替 replace

myString.replaceAll('\n', ' ')