我想将下面的字符串转换为提供的输出。
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"
删除非字母数字字符
下面是从输入字符串中剥离非字母数字字符的/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""
但是它们也会被替换正则表达式删除。
删除非字母数字字符
下面是从输入字符串中剥离非字母数字字符的/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""
但是它们也会被替换正则表达式删除。
问题不在于如何替换字符,而在于如何输入字符串。
只有输入中的第一个反斜杠是反斜杠字符,其他的都是控制字符\r, \b, \f和\n的一部分。
由于这些反斜杠不是单独的字符,而是编写单个控制字符的符号的一部分,因此不能单独删除它们。也就是说,你不能从\n中删除反斜杠,因为它不是两个独立的字符,这是你写控制字符LF或换行的方式。
如果你真的想把输入转换成想要的输出,你需要用相应的字母替换每个控制字符,例如,用字符n替换字符\n。
要替换一个控制字符,你需要使用像[\r]这样的字符集,因为\r在正则表达式中有特殊的含义:
var input = "\\test\red\bob\fred\new";
var output = input
.replace(/[\r]/g, 'r')
.replace(/[\b]/g, 'b')
.replace(/[\f]/g, 'f')
.replace(/[\n]/g, 'n')
.replace(/\\/g, '');
演示:http://jsfiddle.net/SAp4W/