Can't escape apostrophe

Viewed 120

I'm having some trouble escaping an apostrophe in the following javascript code that I am pushing through my webbrowser.

Here is the code that I am using:

tempString1 = "building\'s";
wvMain.EvalScript("frames['main'].document.getElementById('txtInstructions').value='" + tempString1 + "';");

I get this error: Uncaught SyntaxError: Unexpected indentifier.

I have tried doing:

tempString1 = "building" + Convert.ToChar(34) + "s"; //I get the same error

And this:

' gets copied directly into the textfield itself.

does anyone have any advice?

3 Answers

I think the issue is with the joining of string in with the second line. It is evaluating to frames['main'].document.getElementById('txtInstructions').value='building's'; So you will need to add '\' in front of the apostrophe in order to eval correctly.

   tempString1 = "building\\'s";
wvMain.EvalScript(`frames['main'].document.getElementById('txtInstructions').value='${tempString1}';`);

You can escape the value before putting it into your script:

tempString1 = "building\'s";
let tempStringLiteral = `'${tempString1.replace("'", "\\'")}'`;
wvMain.EvalScript("frames['main'].document.getElementById('txtInstructions').value=" + tempString1 + ";");

But I'd recommend looking into the EvalScript method's documentation to see if there's not a more reliable way to pass arguments into it that can be used by the script you give it.

Escaping is unnecessary when you are using double quotes

tempString1 = "building's";

Related