2

I'm assigning the value of JS string variable from server side code.

Like this

var fbShareTitle = "@(ViewBag.LeadTitle as string)";

ViewBag return string value is

A "Fantastic" Lead With 'Qoute'

Now It is giving error in console

SyntaxError: missing ; before statement

I have tried this

var fbShareTitle = ("@(ViewBag.LeadTitle)").replace(/"/g, '\\"');

But now I'm getting this error.

SyntaxError: missing ; before statement

As This string will be shared on fb, So i can't modify string, like replace all " with ' e.t.c.

Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
  • Please post your entire code. – AMACB Jan 14 '16 at 04:54
  • @AMACB since this question is asked so many times there is really no need to post actual code... Something basic search like https://www.bing.com/search?q=C%23+razor+javascript+quotes could have revealed answer... – Alexei Levenkov Jan 14 '16 at 05:47

1 Answers1

1

The reason why your code doesn't work is that Razor will generate the following:

var fbShareTitle = "A "Fantastic" Lead With 'Qoute'";

which is invalid JavaScript. You can't simply fix it by replace, since it's not the problem that your string is bad, it's that your code can't parse - replace never gets to execute. You need to fix it on serverside, where you generate the JavaScript in question, by modifying your Razor code:

var fbShareTitle = @Html.Raw(Json.Encode(ViewBag.LeadTitle as string));

Json will take care of quotes and proper escaping; Raw will make sure you don't get your < and > replaced. Extra benefit from @Html.Raw(Json.Encode(...)) mantra: you can use it to inject any kind of data that can be encoded in JSON, not only strings.

Amadan
  • 191,408
  • 23
  • 240
  • 301