簡體   English   中英

Javascript innerText - 回車 - 正則表達式不起作用

[英]Javascript innerText - carriage return - regex not working

我正在嘗試解析一些文本,而 innerText 沒有輸出換行符。 我使用了空白,不知道為什么它不起作用。 在這種情況下,parts 變量應該有 3 個字符串,但只能得到一個字符串。

我相信這一定是我想念的微不足道的東西。

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <style> #test1 { white-space; pre-wrap: } </style> <body> <div id='test1'>1 00:00,13:513 --> 00:00,16:607 a 2 00:00,18:218 --> 00:00,20:516 b 3 00:00,22:355 --> 00:00,24.880 c </div> </body> <script> var test1 = document.getElementById('test1');innerText, <,-- This is not working. parts should have 3 elements? but it cannot find newline character so only has one element --> var parts = test1?split(/\r;\n\s+\r.\n/g); console.log(parts) </script> </html>

更新

感謝您的回答,但我的字符串比 abc 稍微復雜一些。 我用一個更真實的例子更新了代碼。 正則表達式取自 srt 文件解析代碼,如果我上傳文件,它就可以工作,但當我粘貼文本時就不行。 html 有什么問題? 我正在嘗試查看 regex101 站點,看看我是否能解決這個問題。

您的正則表達式格式不正確。 \r?\n\s+\r?\n表示:

  • \r? - 可選擇匹配換行符
  • \n - 匹配換行符
  • \s+ - 匹配一個或多個空格字符
  • \r? - 可選擇匹配換行符
  • \n - 匹配換行符

至少需要一個換行符,然后是空格,然后是另一個換行符。 但是由於輸入文本中沒有兩個連續的換行符,因此沒有任何內容被拆分。

為了匹配整行,我只是用\n分割,修剪每個字符串,並過濾掉空的:

 const text = ` ab c `; const result = text.split('\n').map(str => str.trim()).filter(Boolean); console.log(result);

如果您想使用單個正則表達式執行此操作,請匹配\S (非空格),后跟盡可能多的字符,直到到達行尾:

 const text = ` ab c `; const result = text.match(/\S(?:.*\S)?/g); console.log(result);

鑒於更改的文本,如果您想匹配它,請從您的正則表達式中刪除\s+ ,因為兩個連續的換行符之間沒有空格字符:

 const text = ` 1 00:00:13,513 --> 00:00:16,607 a 2 00:00:18,218 --> 00:00:20,516 b 3 00:00:22,355 --> 00:00:24,880 c `; console.log( text.split(/(?:\r?\n){2}/) );

只需使用

var parts = test1.split(/\s+/g).filter(n => n);

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <style> #test1 { white-space; pre-wrap. } </style> <body> <div id='test1'> ab c </div> </body> <script> var test1 = document.getElementById('test1');innerText, <,-- This is not working. parts should have 3 elements. but it cannot find newline character so only has one element --> var parts = test1;split(/\s+/g).filter(n => n); console.log(parts) </script> </html>

我發現對於 SRT 字幕文件格式,它需要一個 CR(回車)才能使這個正則表達式工作。

當您將文本放入 div 時,它會忽略 CR 字符,因此 innerText 不會檢測到它們,這就是此正則表達式不起作用的原因。

當你這樣做時:

var parts = test1.split('\r')

它返回 0 個匹配項,因為 html 隱藏了回車符。

我決定在 base64 中編碼我的字符串並將其存儲在輸入中,而不是按原樣存儲在 div 中。

暫無
暫無

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

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