繁星coding
2019-10-15 10:36:36
我想將以下字符串轉換為提供的輸出。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""
但是它們也會被替換的正則表達式刪除。
添加回答
舉報
0/150
提交
取消