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

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"

当前回答

如果你想要这个\\test\red\bob\fred\new字符串,你应该转义所有的反斜杠(\)。当你写\\test\\red\\bob\\fred\\new时,你的字符串实际上只包含一个反斜杠。你可以确定这将打印你的字符串。 因此,如果字符串中的反斜杠被转义,myString.replace(/\W/g, ")将正常工作。

其他回答

删除非字母数字字符

下面是从输入字符串中剥离非字母数字字符的/a正确正则表达式:

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""

但是它们也会被替换正则表达式删除。

目前所有的答案都有怪癖,我能想到的最好的答案是:

string.replace(/[^A-Za-z0-9]/g, '');

下面的例子囊括了我能在键盘上找到的每个键:

var string = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`';
var stripped = string.replace(/[^A-Za-z0-9]/g, '');
console.log(stripped);

产出:“123abcABC”。

您可以使用\p{L}或\p{Letter}查找来自任何语言的字母,使用\d查找数字。

str.replace(/[^\p{L}\d]/gu, '')

^否定字符集:不是\P{L},也不是\d

国旗:

G(全局)执行尽可能多的替换 u (unicode)来识别unicode转义序列(如\p{L})。

例子: 函数removenonalphannumeric (str) { 返回str.replace(/[^\p{L}\d]/gu, ") } 序列= [ “asde5kfjdk ?”, “uQjoFß^ß我霁的美元, '无论3如何?!”, 的ф@ #ево1 ' ] 对于(seq of sequences) { console.log (removeNonAlphaNumeric (seq)) }

这里有一个你可以用的例子,

function removeNonAlphaNumeric(str){
    return str.replace(/[\W_]/g,"");
}

removeNonAlphaNumeric("0_0 (: /-\ :) 0-0");

如果你有除英语以外的其他语言的情况,你需要添加相对块范围从unicode。下面是一个西里尔字母的例子:

.replace(/[^0-9A-Za-z_\u0400-\u04FF]/gi, '')