簡體   English   中英

如何在 javascript 中用空格替換換行符/換行符?

[英]How can I replace newlines/line breaks with spaces in javascript?

我有一個 var,其中包含這種格式的大量單詞(數百萬):

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

我想制作一個 function ,它將用空格替換每個單詞之間的換行符。

所以結果看起來像這樣:

 car house home computer go went

您可以使用.replace() function:

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

請注意,您需要正則表達式上的g標志來獲取 replace 以用空格替換所有換行符,而不僅僅是第一個。

另外,請注意您必須將.replace()的結果分配給一個變量,因為它返回一個新的 string。 它不會修改現有的 string。 Javascript 中的字符串是不可變的(它們不是直接修改的),因此對 string 的任何修改操作(如.slice().concat().replace()等)都會返回一個新的 ZB45CFFE084EDD3D2F2D20。

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

In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use

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

See regex demo

To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:

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

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

  • [ - start of a positive character class matching any single char defined inside it:
    • \r - (\x0D) - \n] - a carriage return (CR)
    • \n - (\x0A) - a line feed character (LF)
    • \x0B - a line tabulation (LT)
    • \x0C - form feed (FF)
    • \u0085 - next line (NEL)
    • \u2028 - line separator (LS)
    • \u2029 - paragraph separator (PS)
  • ] - end of the character class
  • + - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
  • /g - find and replace all occurrences in the provided string.

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

代碼:(固定)

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

一些簡單的解決方案看起來像

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

不需要全局正則表達式,使用replaceAll而不是replace

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM