亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從字符串中刪除非字母數字字符。遇到[\]字符

從字符串中刪除非字母數字字符。遇到[\]字符

我想將以下字符串轉換為提供的輸出。Input:  "\\test\red\bob\fred\new"Output: "testredbobfrednew"我還沒有發現,將處理特殊字符,如任何解決方案\r,\n,\b,等?;旧?,我只是想擺脫所有不是字母數字的東西。這是我嘗試過的...Attempt 1: "\\test\red\bob\fred\new".replace(/[_\W]+/g, "");Output 1:  "testedobredew"Attempt 2: "\\test\red\bob\fred\new".replace(/['`~!@#$%^&*()_|+-=?;:'",.<>\{\}\[\]\\\/]/gi, "");Output 2:  "testedobred [newline] ew"Attempt 3: "\\test\red\bob\fred\new".replace(/[^a-zA-Z0-9]/, "");Output 3:  "testedobred [newline] ew"Attempt 4: "\\test\red\bob\fred\new".replace(/[^a-z0-9\s]/gi, '');Output 4:  "testedobred [newline] ew"嘗試多個步驟function cleanID(id) {    id = id.toUpperCase();    id = id.replace( /\t/ , "T");    id = id.replace( /\n/ , "N");    id = id.replace( /\r/ , "R");    id = id.replace( /\b/ , "B");    id = id.replace( /\f/ , "F");    return id.replace( /[^a-zA-Z0-9]/ , "");}結果Attempt 1: cleanID("\\test\red\bob\fred\new");Output 1: "BTESTREDOBFREDNEW"任何幫助,將不勝感激。工作解決方案:Final Attempt 1: return JSON.stringify("\\test\red\bob\fred\new").replace( /\W/g , '');Output 1: "testredbobfrednew"
查看完整描述

3 回答

?
陪伴而非守候

TA貢獻1757條經驗 獲得超8個贊

刪除非字母數字字符

以下是/正確的正則表達式,用于從輸入字符串中剝離非字母數字字符:


input.replace(/\W/g, '')

請注意,\W這等效于[^0-9a-zA-Z_]-它包括下劃線字符。要刪除下劃線,請使用例如:


input.replace(/[^0-9a-z]/gi, '')

輸入格式錯誤

由于測試字符串包含各種轉義的字符(不是字母數字),因此它將刪除它們。


如果要按字面意義進行處理,則字符串中的反斜杠需要轉義:


"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')

"testredbobfrednew" // output

處理格式錯誤的字符串

如果您無法正確轉義輸入字符串(為什么?),或者它來自某種不受信任/配置錯誤的源,則可以執行以下操作:


JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')

"testredbobfrednew" // output

請注意,字符串的json表示形式包括引號:


JSON.stringify("\\test\red\bob\fred\new")

""\\test\red\bob\fred\new""

但是它們也會被替換的正則表達式刪除。


查看完整回答
反對 回復 2019-10-15
  • 3 回答
  • 0 關注
  • 1148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號