簡體   English   中英

JavaScript 正則表達式空白字符

[英]JavaScript regex whitespace characters

我進行了一些搜索,但在 JavaScript 的正則表達式中找不到包含在\s中的空白字符的明確列表。

我知道我可以依賴空格、換行符、回車和制表符作為空格,但我認為由於 JavaScript 傳統上僅適用於瀏覽器,因此可能是 URL 編碼的空格和 之類的東西。 並且%20也將被支持。

JavaScript 的正則表達式編譯器到底考慮了什么? 如果瀏覽器之間存在差異,我只關心 webkit 瀏覽器,但很高興知道任何差異。 另外,Node.js 呢?

一個簡單的測試:

for(var i = 0; i < 1114111; i++) {
    if(String.fromCodePoint(i).replace(/\s+/, "") == "") console.log(i);
}

字符代碼(Chrome):

9
10
11
12
13
32
160
5760
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8232
8233
8239
8287
12288
65279
["

 [ \f\n\r\t\v\u00A0\u2028\u2029]

HTML != Javascript。 Javascript 完全是文字, %20 是 %20 和&nbsp; 是一串字符 & nbsp 和 ;。 對於字符類,我認為 perl 中幾乎所有 RegEx 都適用於 JS(你不能做命名組等)。

http://www.regular-expressions.info/javascript.html是我使用的參考。

這是primvdb 答案的擴展,涵蓋了整個 16 位空間,包括 unicode 代碼點值以及與 str.trim() 的比較。 我試圖編輯答案以改進它,但我的編輯被拒絕了,所以我不得不發布這個新的。

識別將匹配為空白正則表達式\sString.prototype.trim()的所有單字節字符:

 const regexList = []; const trimList = []; for (let codePoint = 0; codePoint < 2 ** 16; codePoint += 1) { const str = String.fromCodePoint(codePoint); const unicode = codePoint.toString(16).padStart(4, '0'); if (str.replace(/\s/, '') === '') regexList.push([codePoint, unicode]); if (str.trim() === '') trimList.push([codePoint, unicode]); } const identical = JSON.stringify(regexList) === JSON.stringify(trimList); const list = regexList.reduce((str, [codePoint, unicode]) => `${str}${unicode} ${codePoint}\n`, ''); console.log({identical}); console.log(list);

列表(在 V8 中):

0009 9
000a 10
000b 11
000c 12
000d 13
0020 32
00a0 160
1680 5760
2000 8192
2001 8193
2002 8194
2003 8195
2004 8196
2005 8197
2006 8198
2007 8199
2008 8200
2009 8201
200a 8202
2028 8232
2029 8233
202f 8239
205f 8287
3000 12288
feff 65279
["

暫無
暫無

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

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