简体   繁体   中英

How can I get value after hashtag from URL in Java

I have a URL and I want to print in my graphical user interface the ID value after the hashtag. For example, we have www.site.com/index.php#hello and I want to print hello value on a label in my GUI.

How can I do this using Java in Netbeans?

Use the String.split() Method.

public static String getId(string url) {

    return url.split("#")[1];

}

String.split() returns an array of Strings that are delimited, or "Split," by the value you pass to it, or in this case # .

Because you want only the string after the # , you can just use the second item in the array that it returns by adding [1] to the end of it.

For more on String.split() go to Tutorials Point .

By the way, the part of the URL you are referencing is the Element ID. It is used to jump to an Element on a webpage.

Simple solution is getRef() in URL class:

URL url = new URL("http://www.anyhost.com/index.php#hello");
jLabel.setText(url.getRef());

EDIT: According to @Henry comment:

I would recommend to use the java.net.URI as it also deals with encoding. The Javadocs say: "Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL()."

and this comment:

Why not just doing uri.getFragment()

URI uri = new URI("http://www.anyhost.com/index.php#hello");
jLabel.setText(uri.getFragment());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM