I can't get replace / replaceAll to work - java

I need to show data from database that supposed to be shown:
in the html: Behälter
in the browser: Behälter
but instead, I got data like this:
in the html: Behälter
in the browser: Behälter
So I need to change the & back to &. I use replaceAll and replace method from the Java's String class. But it didn't work. I even check whether the String has & or not using indexOf method, but it didn't even seems to catch or even see the & sign.
My code:
// supposed the value returned by the getObject function is "Behälter"
String text = (String)getObject("value");
if (text.indexOf("&") >= 0) text = "abc" + text;
text = text.replace("&", "&");
text = text.replaceAll("&", "&");
if (text.indexOf("&") >= 0) text = text + "def";
text = text + "xyz";
The result is
in the html: Behälterxyz
in the browser: Behälterxyz
Is there anything wrong with how I type and use replace / replaceAll? Thank you for the answer.

I would recommend using Apache Commons Lang for the StringEscapeUtils.unescapeHtml().
Feed it your string with the encoded characters, and it should spit it out decoded.

Related

Dynamically replace part in URL using Regex

I tried searching for something similar, and couldn't find anything. I'm having difficulty trying to replace a few characters after a specific part in a URL.
Here is the URL: https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
I want to remove the /v/ part, leave the t1.0-9, and also remove the /s130x130/.I cannot just replace s130x130, because those may be different variables. How do I go about doing that?
I have a previous URL where I am using this code:
if (pictureUri.indexOf("&url=") != -1)
{
String replacement = "";
String url = pictureUri.replaceAll("&", "/");
String result = url.replaceAll("().*?(/url=)",
"$1" + replacement + "$2");
String pictureUrl = null;
if (result.startsWith("/url="))
{
pictureUrl = result.replace("/url=", "");
}
}
Can I do something similar with the above URL?
With the regex
/v/|/s\d+x\d+/
replaced with
/
It turns the string from
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
to
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t1.0-9/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
as seen here. Is this what you're trying to do?

Base64 Encoded String doesn't matches

Im frustraded. I've got a Basic Http Authorization. For this I set a HttpGetHeader.
This Header needs to be Base64 encoded. I do it like so:
String acc = uname + ":" + pword;
byte[] a = acc.getBytes();
String header = "Basic " + new String(Base64.encode(a, Base64.DEFAULT));
But this encoded String doesn't work. When I log the header, it prints out the same as I need.
It looks the same as String h = "Basic c2NodWsZXI6aGVpbmNA=="; Which is the working one.
But when I compare header.equals(h); or header==h theire both false.
In the end when I set the header to headerit doesn't work, but when I'm using h it works. I guess its sometehing about String encoding but I tried different ways of .getBytes("UTF-8") and similiar (ASCII, UTF-16) but they worked neither.
The username and password are normal chars and numbers.
Can anyone see the mistake? Thanks
Grevius
header.equals(h) returning false indicates that the strings are not identical. header==h shall return false since they are not the same reference.
Empty spaces perhaps? try header.trim().equals(h.trim())
try using base64.encodestring(s)

Javascript for extracting anchor text from anchor tag

need help in the following.
In javascript, need to pass a input
as eg:
str="<a href=www.google.com>Google</a>"; // this is for example actual input vary
// str is passed as parameter for javascript function
The output should retrieve as 'Google'.
I have regex in java and it is working fine in it.
String regex = "< a [ ^ > ] * > ( . * ? ) < / a > ";
Pattern p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
but in javascript it is not working.
how can I do this in Javascript. Can anyone provide me help for javascript implementation.
I dont think you would like to use Regex for this. You may try simply like this:-
<a id="myLink" href="http://www.google.com">Google</a>
var anchor = document.getElementById("myLink");
alert(anchor.getAttribute("href")); // Extract link
alert(anchor.innerHTML); // Extract Text
Sample DEMO
EDIT:-(As rightly commented by Patrick Evans)
var str = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = str;
alert(str1.textContent);
alert( str1.innerText);
Sample DEMO
Insert the HTML string into an element, and then just get the text ?
var str = "<a href=www.google.com>Google</a>";
var div = document.createElement('div');
div.innerHTML = str;
var txt = div.textContent ? div.textContent : div.innerText;
FIDDLE
In jQuery this would be :
var str = "<a href=www.google.com>Google</a>";
var txt = $(str).text();
FIDDLE
From the suggestions given by you all I got answer and works for me
function extractText(){
var anchText = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
alert("hi "+str1.innerText);
return anc;
}
Thanks everyone for the support
Just going to take an initial stab at this, I can update this is you add more tests cases or details to your question:
\w+="<.*>(.*)</.*>"
This matches your provided example, in addition it doesn't matter if:
the variable name is different
the tag or contents of the tag wrapping the text are different
What will break this, specifically, is if there are angle brackets inside your html tag, which is possible.
Note: It is a much better idea to do this using html as other answers have attempted, I only answered this with a regex because that was what OP asked for. To OP, if you can do this without a regex, do that instead. You should not attempt to parse HTML with javascript when possible, and this regex is not comparable to a full html parser.
No need for a regex, just parse the string with DOMParser and get the element and then use the DOM object methods/attributes
var parser = new DOMParser();
var str='<a href='www.google.com'>Google</a>";
var dom = parser.parseFromString(str,"text/xml");
//From there use dom like you would use document
var atags = dom.getElementsByTagName("a");
console.log( atags[0].textContent );
//Or
var atag = dom.querySelector("a");
console.log( atag.textContent );
//Or
var atag = dom.childNodes[0];
console.log( atag.textContent );
Only catch is DOMParser is not supported in IE lower than 9.
Well, if you're using JQuery this should be an easy task.
I would just create an invisible div and render this anchor () on it. Afterwards you could simply select the anchor and get it's inner text.
$('body').append('<div id="invisibleDiv" style="display:none;"></div>'); //create a new invisible div
$('#invisibleDiv').html(str); //Include yours "str" content on the invisible DIV
console.log($('a', '#invisibleDiv').html()); //And this should output the text of any anchor inside that invisible DIV.
Remember, to do this way you must have JQuery loaded on your page.
EDIT: Use only if you've already have JQuery on your project, since as stated below, something simple as this should not be a reason for the inclusion of this entire library.
Assuming that you are using java, from the provided code.
I would recommend you to use JSoup to extract text inside anchor tag.
Here's a reason why. Using regular expressions to parse HTML: why not?
String html = "<a href='www.google.com'>Google</a>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();
String linkHref = link.attr("href"); // "www.google.com"
String linkText = link.text(); // "Google""
String linkOuterH = link.outerHtml();
// "<a href='www.google.com'>Google</a>";
String linkInnerH = link.html(); // "<b>example</b>"

Get URL from string with text

I have a bunch of strings like this:
Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter
And I need to parse this String to two:
Some text, bla-bla
http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter
I need separate them, but, of course, it's enough to parse only URL.
Can you help me, how can I parse url from string like this.
By using split :
String str = "Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter";
String [] ar = str.split("http\\.*");
System.out.println(ar[0]);
System.out.println("http"+ar[1]);
This depends on how robust you want your parser to be. If you can reasonably expect every url to start with http://, then you can use
string.indexOf("http://");
This returns the index of the first character of the string you pass in (and -1 if the string does not appear).
Full code to return a substring with just the URL:
string.substring(string.indexOf("http://"));
Here's the documentation for Java's String class. Let this become your friend in programming! http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Try something like this:
String string = "sometext http://www.something.com";
String url = string.substring(string.indexOf("http"), string.length());
System.out.println(url);
or use split.
I know in PHP you'd be able to run the explode() (http://www.php.net/manual/en/function.explode.php) function. You'd choose which character you want to explode at. For instance, you could explode at "http://"
So running the code via PHP would look like:
$string = "Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter";
$pieces = explode("http://", $string);
echo $pieces[0]; // Would print "Some text, bla-bla"
echo $pieces[1]; // Would print "www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter"

How can I display special chars in an alert box using javascript?

I want to display special chars as an alert box using javascript and jsp...
String encodeString = "ss\ncc";
String test = "DisplayNext('"+encodeString+"')";
String NextLink = "<br> Next";
That is
function DisplayNext(Next){
alert(Next);
}
Though I've used special chars I am not able to display them in an alert box. How can I sort this out?
Your code produce something like this:
<br><a href='#' onclick="DisplayNext('ss
cc');"> Next</a>
And what you need is:
<br> Next
If you want a line break in javascript it must look as \\n in java. So use:
String encodeString = "ss\\ncc";
String test = "DisplayNext('"+encodeString+"')";
String NextLink = "<br> Next";
Also consider using a special function to escape your String objects as javascript values. Google will easily help you find it ;)
If your String is URLEncoded in java you need to unescape it in javascript.
Java:
String s = "ë";
System.out.println(URLEncoder.encode(s, "ISO-8859-1"));
this will print out %EB
Javascript:
alert(unescape('%EB'));
this will print out the character ë in alert message

Categories

Resources