Escape apostrophe passed from code behind - javascript

in ASPX, I call a JS function when clicking on a button, passing in a variable from code behind, something like this:
... onclick="SelectEmpl('<%=employer.Name%>', '<%=employer.Surname%>', '<%=employer.Company%>')"
The problem is, that all parameters passed into the SelectEmpl function are strings and can contain the apostrophe character. In case this happens, the JS apostrophes are paired prematurely and evaluation fails.
I know I need to escape the apostrophes in the strings somehow but I'm not sure how when they are passed from CB.
Thanks

Create a function to escape the apostrophes then call it around each one. Something like:
Shared Function RemoveQuotes(ByVal input As String) As String
Return Replace(input, "'", "\'")
End Function
Then:
... onclick="SelectEmpl('<%=RemoveQuotes(employer.Name)%>', '<%=RemoveQuotes(employer.Surname)%>', '<%=RemoveQuotes(employer.Company)%>')"

Related

losing escape characters passing a path in json from Xamarin Forms c# to javascript

I have a Xamarin Forms app that is calling javascript and sending as a parameter a JSON string that contains a path. When it leaves c# the back slashes have been double-escaped like this:
"myreturnfunc('', '{\"statusCode\":\"200\",\"path\":\"\\\\temp\\\\Uploads\\\\100650\\\\IMG_20200107_094705_5.jpg\"}');"
but when it gets into myreturnfunc only single back slashes remain:
"{"statusCode":"200","path":"\temp\Uploads\100650\IMG_20200107_094705_5.jpg"}"
which fails on JSON.parse. What do I need to do to allow the escaped \'s to come through? I call this method from another javascript function as well, and when called from there it comes through in the correct format:
"{"path":"\\temp\\Uploads\\100650\\IMG_20200107_094705_5.jpg","statusCode":"200"}"
Json.parse typically encounters two escapes when the json.parse parameter contains the transition characters, the first being the escape of the string itself and the second being the escape of the actual js object.
for example,your string \"path\":\"\\\\temp\\\\Uploads\\\\100650\\\\IMG_20200107_094705_5.jpg\" above
First parser extracted strings think first \ escape the second \ and the third \ escape the fourth \, that is to say, the actual output string is "path":"\\temp\\Uploads\\100650\\IMG_20200107_094705_5.jpg" (could be verified by console.log)
Then there is another escape when it is formally converted to a js object,the finally result will be "path":"\temp\Uploads\100650\IMG_20200107_094705_5.jpg"
So if you want one \ in a js object, you need four \ in a json string

RegExp for remove first and last char and turn ending double slashes into single

I have the following Javascript code to obtain the inner string from an RegExp:
Function.prototype.method = function (name,func){
this.prototype[name] = func;
return this;
};
RegExp.method('toRawString', function(){
return this.toString().replace(/^.(.*).$/,"$1");
});
The purpose of this, is to avoid in string double quoting. For example, if you have a Windows file path "C:\My Documents\My Folder\MyFile.file", you can use it like the following:
alert(/C:\My Documents\My Folder\MyFile.file/.toRawString());
However it is not working for ""C:\My Documents\My Folder\" since it causes syntax error. The only way to avoid it is to keep double quoting at the end of the string. Thus it will be written
alert(/C:\My Documents\My Folder\\/.toRawString());
The fact is any odd number of back slashes on the end of the string will be an error, so all ending back slashes must be double escaped. It will not be hard to use a multiple line small implementation, but are there any single RegExp solution?
NOTE
When using toRawString the RegExp object for this is usually NOT going to be used for any other purpose except for that method. I just want to use the syntax of RegExp to avoid double back slashes in source code. Unfortunately the ending double slashes cannot be easily avoid. I think another workaround is to force a space at the end but that is another question then.
UPDATE
I finally solved the "another question" and posted the code here.
OK, I get what you're trying to do! It's hacky : )
Try something like:
return this.toString().slice(1, -1).replace(/\\+$/, '\\')
Hope that helps.
If you want to include the double quotes in the string just wrap it with single quotes.
s = '"C:\\My Documents\\My Folder\\MyFile.file"'
console.log(s) // Output => "C:\My Documents\My Folder\MyFile.file"
This produces a syntax error:
/C:\My Documents\/
But that regular expression could be written correctly like this:
/C:\\My Documents\\/
Or like this:
new RegExp("C:\\\\My Documents\\\\")
I think your function is just fine and is returning a correct result. Regular expressions just can't end with an unpaired backslash. It's not that you're double escaping - you're just escaping the escape character.
This would produce an error too:
new RegExp("C:\\My Documents\\")
A regular expression like this, for instance, can't be written without a pair of backslashes:
/C:\\What/
Without the second backslash, \W would be interpreted as a special character escape sequence. So escaping the escape character isn't only necessary at the end. It's required anywhere it might be interpreted as the beginning of an escape sequences. For that reason, it might be a good rule of thumb to always use two backslashes to indicate a backslash literal in a regular expression.

Unterminated String error while iterating

This is my code :
<c:forEach items="${entry.value}" var="keyval">
var bdgroup= {
elem1: '${keyval.partno}',
elem2: '${keyval.location}',
elem3: '${keyval.village}',
elem4: '${keyval.id}'
};
exampleArray.push(bdgroup);
</c:forEach>
i am getting
'unterminated string literal error'`
sometimes it works fine but for other times this error happens..
When e.g. ${keyval.id} gets expanded, if it has a single quote in it, then the Javascript will look like
elem1: 'what's up?'
thus your unterminated string error.
Escape the quotes before you put them in JSON.
Escape the single quotes and any other special characters, so that the values are taken correctly.
I'm ==> I\'m
Looks like you're using a taglib, and the elements inside the single quotes are being generated by the page processor.
I'll bet that on the times that it fails, your values contain single quotes.
Escape the single quotes, and that should fix it.

Value unexpectedly changes while sending from jsp to javascript function

I have a piece of code in jsp:
String temp=new SimpleDateFormat("MMddyyyy").format((java.sql.Date)ppdates.get(authShown));
out.print(temp);
<select id="pcol<%=i%><%=weekNo%><%=au%>" onChange="pSelectedAuth(<%=i%>,<%=weekNo%>,<%=au%>,<%=currentEmployee%>,<%=temp%>)">
This prints 06042012 on the screen.
Now, my javascript functions are below:
function pSelectedAuth(formID,weekNo, index, currentEmployee,startDate){
alert(formID+":"+weekNo+":"+index+":"+currentEmployee+":"+startDate);
onchange, this alert shows 1623050
Does anyone has any idea how to get my 06042012 back?
You're not doing anything to quote your arguments (that is — you're not wrapping them in '...' or "..."), so they're being interpreted as JavaScript expressions. In JavaScript source-code, 06042012 is interpreted as a base-8 integer (because of the leading 0), so it denotes 1623050.
To fix this, be sure to wrap your JavaScript strings in '...' or "..." (as well as to properly escape any internal quotation-marks, backslashes, newlines, special characters, </, and so on). That way, you'll have '06042012' or "06042012", which JavaScript will interpret as a string, like you want.

Escaping quotes from Rails Variables when using them for Javascript?

I am having problems when trying to use a rails variable within javascript code.
For example, I might define a link_to_remote, with parameter
:complete => "alert('my_var');"
If my_var = "I'm testing.", then the javascript code will break due to the single quote closing the code prematurely. If I try using escape_javascript(my_var) so that the quote gets turned into \', it doesn't seem to fix the problem.
I've noticed that when you try alert('I\'m testing'); there's a problem, but if you do alert('I\\'m testing'), it works. Since escape_javascript only turns ' into \', rather than \\', does somebody have a suggestion for how to handle this?
Thanks!
Eric
when you try alert('I\'m testing'); there's a problem
Backslash is also an escape in Ruby strings! So the string literal:
"alert('I\'m testing');"
means the string:
alert('I'm testing');
the backslash is gone already before JavaScript gets a look at it. When you are writing a JavaScript string literal inside a Ruby string literal you need to escape the escape, \\, to get a real \ that will then, in JavaScript, escape the apostrophe.
escape_javascript correctly generates the backslash for JavaScript, if a backslash was included in its input. But again, if you're writing a string literal, you have to escape the backslash to get a real backslash:
escape_javascript("\b") -> this is a backspace character!
escape_javascript("\\b") -> this is backslash-then-letter-b;
escaped for JavaScript literal to double-backslash-then-b.
So, this is fine:
"'"+escape_javascript(myvar)+"'"
alternatively, you can use a JSON encoder to create the JavaScript string literal including the surrounding quotes.

Categories