gpt4 book ai didi

java - 如何在 gwt 中使字符串中的 url 可点击

转载 作者:行者123 更新时间:2023-11-29 04:52:37 25 4
gpt4 key购买 nike

如果我有这样的字符串:

String textWithUrl = "I am a string and http://www.google.com is the url to google";

然后我把它放在一个 HTML 元素中:

HTML html = new HTML(textWithUrl);

但是链接是不可点击的。通常我让它可以点击(从未用 Label 测试过):

private String makeUrlInTextClickable(String text) {

if (text == null) return "";

String[] words = text.split(" ");
String textWithUrl = text;

for (String word : words) {
// Maybe more checks are needed to prevent typos like abcdhttp://
// Mostly the texts come from a source, in which the urls are likely to be valid
if (word.toLowerCase().contains("http://")) textWithUrl = textWithUrl.replace(word, "<a target=\"_blank\" href=\"" + word + "\">" + word + "</a>");
}

return textWithUrl;
}

textWithUrl 可以是任意长度,里面有很多 url。

有更好的方法吗?

编辑:

示例用法:

public class Test implements EntryPoint {

@Override
public void onModuleLoad() {

String textWithUrl = "I am a string and http://www.google.com is the url to google";
RootPanel.get().add(new HTML(makeUrlInTextClickable(textWithUrl)), 0, 0);
}
}

输出将只是一个带有可点击的 google url 的 HTML 小部件

最佳答案

这不是特定于 GWT 的,但是有大量的 JavaScript 库可以满足您的需求。由于您可以简单地从 GWT 中包含和调用 JS,因此这对您来说应该是一个可行的解决方案。

这里有关于这个主题的 SO 答案:

How to replace plain URLs with links?

但为了完整性,这些是推荐的库:

两者都有现场演示功能,您可以在其中自行测试。显然,它们都无法涵盖您的边缘情况,但仍然值得一看。

关于java - 如何在 gwt 中使字符串中的 url 可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34851021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com