简体   繁体   English

如何为 .attr("href") 添加前缀?

[英]How to add prefix to .attr("href")?

I need to add prefix string to my link with is returned by attribute "href".我需要在我的链接中添加前缀字符串,由属性“href”返回。

.getElementsByClass(CLASS_OFFER_NAME)
.firstOrNull()
?.attr("href") // Here need I add prefix to attr href
.orEmpty()

I getting now url eg: work/london/22 but I need add prefix with domain so I want to get www.offerlist.com/work/london/22我现在得到 url 例如:work/london/22 但我需要用域添加前缀所以我想得到 www.offerlist.com/work/london/22

May be you can convert String?可能是你可以转换String? to Optional<T> and apply prefix concatenation though Optional.map method and finally extract the resulting value using orElse("") ...Optional<T>并通过Optional.map方法应用前缀连接,最后使用orElse("")提取结果值...

This is a functional approach to the problem, but you can obviously solve it via if or ternary or elvis operator applied to the value returned by orEmpty .这是解决问题的函数式方法,但您显然可以通过if三元elvis 运算符应用于orEmpty返回的值来解决它。

If you like the functional approach, you can give a try to this example, which shows both Optional and T?如果你喜欢函数式方法,你可以试试这个例子,它同时显示了 Optional 和 T? --> Optional use cases: --> 可选用例:

fun <T> toOptional(value : T?) : Optional<T> {
    if(value == null) {
        return Optional.empty()
    }
    return Optional.of(value)
}

val opt:Optional<String> = Optional.empty()
println(opt.map { x -> "PREFIX/$x" }.orElse(""))
val opt2:Optional<String> = Optional.of("link")
println(opt2.map { x -> "PREFIX/$x" }.orElse(""))
var str : String? = null
println(toOptional(str).map { x -> "PREFIX/$x" }.orElse(""))
var str2  = "hrefValue"
println(toOptional(str2).map { x -> "PREFIX/$x" }.orElse(""))

I hope this can help!我希望这能有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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