[英]How to remove extra lines in paragraphs
我有這個從api調用的信息:
例如,
"
1. Assist food and technology department in record keeping and filing"
如何刪除額外的線?
通常,有3種類型的東西會產生不需要的新行:
\\n
\\r
<br/>
標簽 JavaScript支持regex及其replace()
函數:
s = s.replace(/[\r\n]+|<br *\/?>/g, " ");
注1:我加了一個?
后/
中的<br/>
標記,因為很多瀏覽器不插入字符,所以它很可能不存在。
注2:我在換行符之前和之后的任何內容之間放置一個空格,這意味着單詞仍將按預期分開。
如果要從字符串的開頭和結尾進行修剪,可以使用:
s = s.replace(/^(<br *\/?>| |\t|\n|\r|\v|\f| | | )+/, "")
.replace(/(<br *\/?>| |\t|\n|\r|\v|\f| | | )+$/, "");
請注意, \\s+
可能包括也可能不包括它們在我的正則表達式中出現的所有字符。 事情的出現取決於使用的瀏覽器。
只需刪除字符串開頭和結尾的所有空格。 這就是.trim()
作用:
s = ` 1. Assist food and technology department in record keeping and filing `; s = s.trim(); console.log(s);
trim()
的替代方法(如果您的瀏覽器不支持它?)將是一個正則表達式:
s = '\\n\\n1. Assist food and technology department in record keeping and filing \\n \\r\\n '; s = s.replace(/^[\\s\\\xA0]+|[\\s\\\xA0]+$/g, ''); console.log(s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.