0
<script>
var text = "a's ..a's ...\"... ";
text = convert(text);
function convert( text )
{
 var n = text.replace(/\'/g, "&#039;");
 n = text.replace(/\"/g,"&quot;");
 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
0

2 Answers 2

4

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, "&#039;");
 n = n.replace(/\"/g,"&quot;");
 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, "&#039;").replace(/\"/g,"&quot;");
answered Sep 11, 2012 at 14:33
Sign up to request clarification or add additional context in comments.

Comments

1
function convert( text )
{
 var n = text.replace(/\'/g, "&#039;");
 // Wrong: n = text.replace(/\"/g,"&quot;");
 // This modifies the previously edited variable.
 n = n.replace(/\"/g,"&quot;");
 return n;
}
answered Sep 11, 2012 at 14:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.