从字符串中删除非字母数字字符。遇到[\]字符

我想将以下字符串转换为提供的输出。


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"


鸿蒙传说
浏览 566回答 3
3回答

喵喔喔

删除非字母数字字符以下是/正确的正则表达式,用于从输入字符串中剥离非字母数字字符: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""但是它们也会被替换的正则表达式删除。
打开App,查看更多内容
随时随地看视频慕课网APP