You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写函数判断href链接是否跳转到新页面?

如何判断href是否跳转到新页面

我需要实现一个名为linksToAnotherPage的函数,接收href参数,判断该链接是跳转到新页面,还是属于tel:、mailto:、#锚点这类不会跳转到新页面的类型。

function linksToAnotherPage(href) {
 ....
}

linksToAnotherPage('tel:123-456-7890') -> // false
linksToAnotherPage('contact') -> // true

两类链接示例

<!-- 不会跳转到新页面的链接 -->
<a href="tel:123-456-7890">123-456-7890</a>
<a href="mailto:email@example.com">Send Email</a>
<a href="#start-now">Start Now</a>

<!-- 跳转到新页面的链接 -->
<a href="contact">Send Email</a>

当前解决方案

function isInteractiveHref (href) {
    return (
        href.startsWith("mailto:") || href.startsWith("tel:") || 
        href.startsWith("#")
    )
}

isInteractiveHref(props.href) ? (
    <Link href={props.href}>
        <a>Does not link to another page</a>
    </Link>
) : <Link href={'/' + props.href}>
        <a> Links to another page</a>
    </Link>

内容的提问来源于stack exchange,提问作者user19666029

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:46:02