为什么此代码无法替换特殊字符:

http://jsfiddle.net/TTfzu/26/

var strOutput = 'aaa { " } ';

strOutput.replace(/{/g, "");
strOutput.replace(/}/g, "");
strOutput.replace(/"/g, "");

document.write( strOutput );


需要更改什么?

最佳答案

replace不会更改其参数,它将返回一个新字符串。您必须将结果分配到其他地方,否则会丢失:

var strOutput = 'aaa { " } ';

strOutput = strOutput.replace(/{/g, "");
strOutput = strOutput.replace(/}/g, "");
strOutput = strOutput.replace(/"/g, "");

document.write( strOutput );


或者只在正则表达式中使用字符类[...]

var strOutput = 'aaa { " } ';
strOutput = strOutput.replace(/[{}"]/g, "");

09-11 18:58