<script>
var text = "a's ..a's ...\"... ";
text = convert(text);
function convert( text )
{
var n = text.replace(/\'/g, "'");
n = text.replace(/\"/g,""");
return n;
}
console.log(text);
document.write(text);
</script>
The problem is that when it replace the second time it take doesnt "remember" what it replaced the first time, so only the last replace is returned.
asked Sep 11, 2012 at 14:31
Dennis Sødal Christensen
2251 gold badge4 silver badges15 bronze badges
2 Answers 2
That's because you are replacing the original text string in the second replace, instead of n, which is the value of the replaced text:
function convert( text )
{
var n = text.replace(/\'/g, "'");
n = n.replace(/\"/g,""");
return n;
}
replace does not modify your original string. Instead, it returns a new modified string . You can also do both replaces in a single statement:
return text.replace(/\'/g, "'").replace(/\"/g,""");
answered Sep 11, 2012 at 14:33
João Silva
91.8k29 gold badges156 silver badges158 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
function convert( text )
{
var n = text.replace(/\'/g, "'");
// Wrong: n = text.replace(/\"/g,""");
// This modifies the previously edited variable.
n = n.replace(/\"/g,""");
return n;
}
answered Sep 11, 2012 at 14:33
Waleed Khan
11.5k7 gold badges41 silver badges70 bronze badges
Comments
lang-js