I am trying to pass a string from my java code to javascript like so:
myData.data = "${data.myString}";
This breaks if myString contains a "
I tried storing a javascript safe string instead, just replacing " with \" but then when I use myString in my jsp I get an ugly output with \" showing instead of "
What is the best way to safely pass a string and not mess up the rest of my output.
Encode it into the html in the JSP:
<input id="test_hide" type="hidden" value="${URIUtil.encodeAll("http://www.google.com?q=a b","UTF-8")}">
Then in the JavaScript:
myData.data = decodeURIComponent(document.getElementById('test_hide').getAttribute('value'));
Java - Convert String to valid URI object
Replacing the double quotes with " should work
A bad solution :
Check if your string has double quotes, if yes then use
myData.data = '${data.myString}';
if it contains single quotes use
myData.data = "${data.myString}";
This will explode if you have both single and double quotes.
A good solution :
Just use
"
Related
The user input a String through the scanner and the format of String is "Testing" (quoted with “”) .
Just like C:\> "Testing"
I'd like to save the text as a String without double quotes. How do I catch the text in the middle of quotes?
Please lookup basic Java string manipulation.
A few approaches in Java:
Use .substring(1, length-1)
Use .replaceAll(“\”,””)
Use regular expression in Java and extract contents between “(.*)”
Show us what you’ve tried
If the double quotes are always present at the start and end
Then
s= s.substring(1,s.length()-1);
else you can try
if(s.charAt(0)=='"'){
s=s.substring(1,s.length());
}
if(s.charAt(s.length()-1)=='"'){
s=s.substring(0,s.length()-1);
}
I want to pass some text by adding double quotes before and after.
I have a retrieved some text(url) from my json array like https://xyzabc and i have stored it in a string.
now i have to add some certificate and some response to that url and trying to retrieve some another data from it(new URL).
Here Iam trying to pass like String newUrl = oldurl+response+certificate
And i have to pass the url in double quotes(must in double quotes) if iam passing like String newUrl = "oldurl+response+certificate", the total is considering as one string so i have to append double quotes before and after the newUrl string without make it as a single String.
I have tried some "\"newUrl""\ but it doent work for me...Suggest me some solution.
Try this:
newUrl = "\""+oldurl+response+certificate+"\"";
Hope it helps:)
Use temporary special character in string literal and convert it into quotation like
String newUrl = ("$"+oldurl+response+certificate+"$").replaceAll('$','"');
You can use regular expression -
String str="\"yourstring here\""
I am receiving the data from the service with the escape sequence characters...I have managed to elemenate them by this code
results=results.replace("\\\"", "\"");
if(results.startsWith("\"")) {
results=results.substring(1,results.length());
}
if(results.endsWith("\"")) {
results=results.substring(0,results.length()-1);
}
It works fine but for some strings it throws exception while creating json object...How do I automatically unescape the escape characters in the result, I have searched for answers but many of them saying to use a third party library...what is the best I can achieve this.
I think Apache Commons work pretty good. It has StringEscapeUtils class with bunch of different static methods for escaping and unescaping strings, so i think you should check it.
Good luck!
place this part of code below the parsing Array
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
here for me content is object, replace according to ur necessary in the place of "content".
Trying to get a simple string replace to work using a Groovy script. Tried various things, including escaping strings in various ways, but can't figure it out.
String file ="C:\\Test\\Test1\\Test2\\Test3\\"
String afile = file.toString() println
"original string: " + afile
afile.replace("\\\\", "/")
afile.replaceAll("\\\\", "/") println
"replaced string: " + afile
This code results in:
original string: C:\Test\Test1\Test2\Test3\
replaced string: C:\Test\Test1\Test2\Test3\
----------------------------
The answer, as inspired by Sorrow, looks like this:
// first, replace backslashes
String afile = file.toString().replaceAll("\\\\", "/")
// then, convert backslash to forward slash
String fixed = afile.replaceAll("//", "/")
replace returns a different string. In Java Strings cannot be modified, so you need to assign the result of replacing to something, and print that out.
String other = afile.replaceAll("\\\\", "/")
println "replaced string: " + other
Edited: as Neftas pointed in the comment, \ is a special character in regex and thus have to be escaped twice.
In Groovy you can't even write \\ - it is "an unsupported escape sequence". So, all answers I see here are incorrect.
If you mean one backslash, you should write \\\\. So, changing backslashes to normal slashes will look as:
scriptPath = scriptPath.replaceAll("\\\\", "/")
If you want to replace pair backslashes, you should double the effort:
scriptPath = scriptPath.replaceAll("\\\\\\\\", "/")
Those lines are successfully used in the Gradle/Groovy script I have intentionally launched just now once more - just to be sure.
What is even more funny, to show these necessary eight backslashes "\\\\\\\\" in the normal text here on StackOverflow, I have to use sixteen of them! Sorry, I won't show you these sixteen, for I would need 32! And it will never end...
If you're working with paths, you're better off using the java.io.File object. It will automatically convert the given path to the correct operating-system dependant path.
For example, (on Windows):
String path = "C:\\Test\\Test1\\Test2\\Test3\\";
// Prints C:\Test\Test1\Test2\Test3
System.out.println(new File(path).getAbsolutePath());
path = "/Test/Test1/Test2/Test3/";
// Prints C:\Test\Test1\Test2\Test3
System.out.println(new File(path).getAbsolutePath());
1) afile.replace(...) doesn't modify the string you're calling it on, it just returns a new string.
2) The input strings (String file ="C:\\Test\\Test1\\Test2\Test3\\";), from Java's perspective, only contain single backslashes. The first backslash is the escape character, then the second backslash tells it that you actually want a backslash.
so
afile.replace("\\\\", "/");
afile.replaceAll("\\\\", "/");
should be...
afile = afile.replace("\\", "/");
afile = afile.replaceAll("\\", "/");
In Groovy you can use regex in this way as well:
afile = afile.replaceAll(/(\\)/, "/")
println("replaced string: "+ afile)
Note that (as Sorrow said) replaceAll returns the result, doesn't modify the string. So you need to assign to a var before printing.
String Object is immutable so if you call a method on string object that modifies it. It will always return a new string object(modified). So you need to store the result return by replaceAll() method into a String object.
As found here, the best candidate might be the static Matcher method:
Matcher.quoteReplacement( ... )
According to my experiments this doubles single backslashes. Despite the method name... and despite the slightly cryptic Javadoc: "Slashes ('\') and dollar signs ('$') will be given no special meaning"
I am doing the following:
String url = String.format(WEBSERVICE_WITH_CITYSTATE, cityName, stateName);
String urlUtf8 = new String(url.getBytes(), "UTF8");
Log.d(TAG, "URL: [" + urlUtf8 + "]");
Reader reader = WebService.queryApi(url);
The output that I am looking for is essentially to get the city name with blanks (e.g., "Overland Park") to be formatted as Overland%20Park.
Is it this the best way?
Assuming you are actually wanting to encode your string for use in a URL (ie, "Overland Park" can also be formatted as "Overland+Park") you want URLEncoder.encode(url, "UTF-8"). Other unsafe characters will be converted to the %xx format you are asking for.
The simple answer is to use URLEncoder.encode(...) as stated by #Recurse. However, if part or all of the URL has already been encoded, then this can lead to double encoding. For example:
http://foo.com/pages/Hello%20There
or
http://foo.com/query?keyword=what%3f
Another concern with URLEncoder.encode(...) is that it doesn't understand that certain characters should be escaped in some contexts and not others. So for example, a '?' in a query parameter should be escaped, but the '?' that marks the start of the "query part" should not be escaped.
I think that safer way to add missing escapes would be the following:
String safeURI = new URI(url).toASCIIString();
However, I haven't tested this ...