0

I have an asp.net-mvc view and I am generating a javascript array like this from my view model:

 var jsDict = new Array();
 <% foreach (var myEvent in Model.MyEvents) { %>
      jsDict['<%=myEvent.Date.ToString("yyyy-MM-dd") %>'] = '<%=myEvent.Title %>';
 <% } %>

The issue is that in some cases

 myEvent.Title

has an apostrophe in it so it breaks the string.

For example

jsDict['2015-01-01'] = 'Test is my 'first' test';

what is the correct way to escape around the word first above to make this a valid array.

I tried to change it to double quotes instead of apostrophes

 jsDict["2015-01-01"] = "Test is my 'first' test";

which seems to work but I have a fear that some of the event Titles would have a double quote it in so I want a solution that works for both apostrophe and double quotes.

1 Answer 1

2

Escape the apostrophes as \', and also escape backslashes as \\:

jsDict['<%=myEvent.Date.ToString("yyyy-MM-dd") %>'] = '<%=myEvent.Title.Replace("\\", "\\\\").Replace("'", "\\'") %>';

If the string can contain control characters, you need to replace them too, for example adding .Replace("\n", "\\n").

Sign up to request clarification or add additional context in comments.

Comments

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.