I have a string that must be used to be passed into a JavaScript function. I have tried many ways, but I still cannot make it to work.
<%=name%>
The name field is a string that contains single quotes such as It's Morning. I have tried to use:
String nameString = rs.getString("name");
nameString = nameString.replaceAll("'","\'");
<%=nameString%>
And also
nameString = URLEncoder.encode(nameString);
And also
nameString = nameString.replaceAll("'","'");
And also
nameString = nameString.replaceAll("'","'");
I still cannot get it to work. And also I can't go for EL.
If you want to replace a single quote (') in a String with a JavaScript-escaped (backslashed) single quote (\') in Java code then you need to escape the backslash character (with a backslash!). For example:
nameString = nameString.replaceAll("'","\\'");
See also: String.replaceAll single backslashes with double backslashes
Try to use String.fromCharCode(39) instead of single quote, String.fromCharCode(39) is ASCII codes for single quote.
If you are doing it inside JSP tag, you need to have sufficient backslashes for one of them to actually make it into the web page. The code would be:
<%=nameString%>
You need one backslash to escape the other backslash and each of those needs to be escaped - hence four backslashes (yuck).
Hope that helps.
The following worked for me, as the HTML encoding is done before the function call and replaced the single quote with '.
nameString = nameString.replaceAll("'","\\'");
Related
I believe that this is simple and I'm missing something. I want to split a physical path in windows with javascript. So I try with String#split function, but my result was inespected.
For this string
"C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf"
I'm getting this result
var test = "C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf";
test.split("\"); //throws error
test.split("\\"); //result in -> ["C:CLCVIDAWeb_REPOSITORIOColectivosReembolsosWebTMP_011906169_01_01.pdf"]
test.split(/\\/); // -> the regex is the same as above
One last thing, in my test, I found that to get the result that I want I could do it like this
var test2 = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf"
test2.split("\\"); // -> ["C:", "CLC", "VIDA", "Web", "_REPOSITORIO", "Colectivos", "ReembolsosWeb", "TMP_011906169_01_01.pdf"]
So my question is, how can I split the string from test var to get the array from the last case?
Strings in javascript support escape sequences via the backslash (\). For example if you need a tab in your string you can add a \t anywhere in your string and it will be replaced with a tab, a \n will be replaced with a new line.
The backslashes in test are either converted to their respective characters or dropped because they are invalid escape sequences.
To get around this you can escape one backslash with another to get a single normal backslash. The downside is that this cannot be done in javascript. Generally I paste my string in to notepad/N++/Code/Sublime and replace all \ with \\
Since you are hard coding the string you need to escape all backslashes. After that you can use test.split("\\") which, itself contains an escaped backslash.
So, as far as Javascript is concerned, your code looks like this.
var test = "C:CLCVIDAWeb_REPOSITORIOColectivosReembolsosWebTMP_011906169_01_01.pdf";
To make javascript see the string correctly you need to make it look like this...
var test = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf";
Firstly, note that when you have a single backslash in a string, it is used for escaping the next character. It is just ignored if there is no special character next to it to escape.
Now, just have a look at your string :
var test = "C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf"
Don't you think all of your single backslashes will be ignored here?
So, the solution is simple, what you have already tried successfully. To escape all your backslashes with another backslash.
var test2 = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf"
test2.split("\\"); // -> ["C:", "CLC", "VIDA", "Web", "_REPOSITORIO", "Colectivos", "ReembolsosWeb", "TMP_011906169_01_01.pdf"]
But, are you worried about any dynamic data which has such backslash? (For example, coming from a text input or a file input.) Don't think about escaping the backslash inside it. Because you don't need to do that! It's already a well formatted string for you, which you can use as it is. You need to escape only when you are hard coding the string yourself.
In my script I have:
xmlFile = "C:\Timelines\Data\AKM.XML"
alert(xmlFile)
The alert displays as :
C:TimelinesDataAKM.XML
The line defining xmlFile is written into the script by an external program. But I have tried deleting it, and rekeying with NotePad, with same result.
TIA
Andrew
Backslashes are used to escape special characters. As in this case none of them are followed by known escape codes, they are ignored.
To escape the backslash itself to show an actual backslash, repeat it:
xmlFile = "C:\\Timelines\\Data\\AKM.XML"
Try this
xmlFile = "C:\\Timelines\\Data\\AKM.XML"
Because \ will be take it as escape character
Say I have a string variable (var str) as follows-
Dude, he totally said that "You Rock!"
Now If I'm to make it look like as follows-
Dude, he totally said that "You Rock!"
How do I accomplish this using the JavaScript replace() function?
str.replace("\"","\\""); is not working so well. It gives unterminated string literal error.
Now, if the above sentence were to be stored in a SQL database, say in MySQL as a LONGTEXT (or any other VARCHAR-ish) datatype, what else string optimizations I need to perform?
Quotes and commas are not very friendly with query strings. I'd appreciate a few suggestions on that matter as well.
You need to use a global regular expression for this. Try it this way:
str.replace(/"/g, '\\"');
Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
onclick= "_deleteWPSchemeData(${viewWPMasterGrid.id}, '${viewWPMasterGrid.name}')"
${viewWPMasterGrid.name} retutrns me a string(for e.g. W.P.WINT OFF ALL'10) which often has single quote character so from the calling javascript method I am not getting the second parameter at all. How to deal with problem?
When a dynamic String can be put inside a JavaScript string literal, it should be JS-escaped. Just as when a dynamic String is put inside a HTML page, it's HTML-escaped.
Use commons-lang StringEscapeUtils.escapeECMAScript (or escapeJavaScript depending on the version) to escape the String. You could create a very simple EL function to do that straight from the JSP.
Note that you could have problems with single quotes, but also double quotes, tags, EOLs, backslash, which must all be escaped in a JS String literal.
It looks like you could split the second parameter out into its own variable first. If I have understood your question correctly.
var viewWPMasterGridName = "${viewWPMasterGrid.name}";
onclick = "_deleteWPSchemeData(${viewWPMasterGrid.id},'" + viewWPMasterGridName + "')";
Use '${viewWPMasterGrid.name.replaceAll("'", "\'")}'
try this,
var name = "${viewWPMasterGrid.name}".replace(/'/g,"\\'");
I have a web application where I am dynamically creating a url. The url has a parameter and I must pass a double quote. I have tried this all different ways but it is still not working. Anybody have any ideas?
To create the URL:
searchSurveyDetail.setSurveyFormURL(surveyDetail.getSurveyFormURL()+"#search="+ "\"" + searchValue + "\"");
on the Page:
onClick="window.open('${surveyDetail.surveyInstructionsURL}')"
The result:
onClick="window.open('http://www.mytest.com/survey1.pdf#search="company"')"
The short answer is you need to double escape the double quotes. So you need:
searchSurveyDetail.setSurveyFormURL(surveyDetail.getSurveyFormURL()+"#search="+ "\\\"" + searchValue + "\\\"");
which produces:
onClick="window.open('http://www.mytest.com/survey1.pdf#search=\"company\"')"
which will escape the quotes properly.
Couple of things to keep in mind:
This doesn't take care of double quotes in the search term itself. Make sure you escape that.
I'm not sure why you want to wrap the search term in double quotes. For a typical search url, you'll want a query string like: search=term not search="term" because you'll just end up stripping the quotes later. But maybe you need that for some reason.
I gather you're using PHP on the server side? In that case you should run the URL through htmlspecialchars() before concatenating it to the HTML.