79260168

Date: 2024-12-07 07:36:51
Score: 2
Natty:
Report link

I just wrote a short and simple function which can automatically detect links/hyperlinks in your text/string and convert them into clickable links/hyperlinks.

It uses the newly introduced LinkAnnotation (unlike the deprecated ClickableText).

The regex matches all the possible combinations of a valid URL format.

fun linkifiedText(str: String): AnnotatedString {
    val urlRegex = Regex("\\b((https?://)?([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}(:\\d+)?(/\\S*)?)\\b")
    val matches = urlRegex.findAll(str).map { it.range }
    var lastIntRangeIndex = 0
    return buildAnnotatedString {
        matches.forEach { intRange ->
            append(str.slice(IntRange(0, intRange.first - 1)))
            withLink(
                LinkAnnotation.Url(
                    if (str.slice(intRange)
                            .startsWith("www")
                    ) "https://" + str.slice(intRange) else str.slice(intRange),
                    TextLinkStyles(
                        style = SpanStyle(
                            color = Color.Blue,
                            textDecoration = TextDecoration.Underline
                        )
                    )
                )
            ) {
                append(str.slice(intRange))
            }
            lastIntRangeIndex = intRange.last + 1
        }
        append(str.slice(IntRange(lastIntRangeIndex, str.length - 1)))
    }
}

The usage is pretty simple

Text(text = linkifiedText("your_text"))

Any optimization suggestions are appreciated

Reasons:
  • Blacklisted phrase (1): appreciated
  • RegEx Blacklisted phrase (2): Any optimization suggestions
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Aaron