1

I have:

function showMessage(message) {
    alert(message);
}

But when the message comes dynamically from the server as(example): "Men's" it doesn't work.

I've tried:

function myEncode(message) {
    return message.replace("'", "\'");
}

showMessage(myEncode(message));

Doesn't seem to work. This is a simple example, the actual code is more complicated, but essentially this is the issue.

5
  • 1
    A good read: en.wikipedia.org/wiki/JSON Commented Jun 27, 2013 at 9:02
  • 3
    I assume your problem is that your server-generated code results in something like showMessage(myEncode('Men's'))? So your JavaScript is already broken at that point - so trying to replace something in JavaScript if you already have a JS syntax error is of course pointless (D'oh!). Do the escaping in your server-side code before you output that value as a JS string value. Commented Jun 27, 2013 at 9:07
  • Yes, it actually comes broken from the server side. Commented Jun 27, 2013 at 9:09
  • 1
    Can't you fix it on the server? That would be more logical I think, than patching it in JavaScript. Why not use something that both your server and client can understand, such as JSON? This doesn't seem like the right approach... Commented Jun 27, 2013 at 9:12
  • Indeed the problem was server side. Thanks for the tip ! Commented Jun 27, 2013 at 9:35

1 Answer 1

1

You should specify the g parameter, for a global replace (not only the first match).

You should also escape the slash:

function myEncode(message) {
    return message.replace(/'/g, "\\'");
}
Sign up to request clarification or add additional context in comments.

1 Comment

this just replaces ' by ' you need to write "\\'"

Your Answer

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.