Shlomo
Shlomo

Reputation: 3990

Javascript replace special chars { } "

Why does this code fail replacing the special chars:

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

var strOutput = 'aaa { " } '; 

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

document.write( strOutput );

What needs to be changed?

Upvotes: 0

Views: 381

Answers (3)

Andreas Louv
Andreas Louv

Reputation: 47099

You will need to catch the result from the replace. (And you can chain your replaces.)

var strOutput = 'aaa { " } '; 

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

document.write( strOutput );

Btw you can make it as simple as this:

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

As of @Alnitak comment:

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

Upvotes: 3

georg
georg

Reputation: 214949

replace doesn't change its argument, it returns a new string. You have to assign the result somewhere otherwise it's lost:

var strOutput = 'aaa { " } '; 

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

document.write( strOutput );

or just use a character class [...] in your regexp:

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

Upvotes: 4

Alnitak
Alnitak

Reputation: 339786

Per other answers, you need to use the result of .replace.

However you don't need three calls, you should be using:

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

where the [...] is a character class which matches any individual character in that set. Within such a class the only characters that need to be escaped are ^-]\

Upvotes: 1

Related Questions