首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用链接替换GitHub用户名

用链接替换GitHub用户名
EN

Code Review用户
提问于 2019-04-01 20:30:35
回答 1查看 56关注 0票数 3

一个用户写了一个问题,询问是否在bio (或任意标记)中,任何有标记的帐户都可以自动链接,就像在Github上一样。

我给了他们这个功能:

代码语言:javascript
复制
    let bio = "The coolest company to work for is @github!  There is also @aws and @microsoft.";
    let linkedBio = "";
    let found = false;
    let link = "";
    for (let i = 0; i < bio.length; i++) {
      let currentChar = bio[i];

      if (currentChar.startsWith("@")) {
        link += currentChar;
        found = true;
        continue // we don't need to look at other chars until next iterations
      }

      if (found) {
        if (/[^A-Za-z0-9]/.test(currentChar)) { // we found the end of the link (you can add more special chars to this)
          let tag = "<a href=https://github.com/" + link.substr(1) + ">" + link + "</a>"
          linkedBio += tag + currentChar // we add the special char at the end of the tag so that it actually appears, otherwise it does not
          link = "";
          found = false;
        } else {
          link += currentChar;
        }
      } else {
        linkedBio += currentChar;
      }
    }

    if (link.length > 0) { // means we need to add a link that is the last possible thing without anything after it
      let tag = "<a href=https://github.com/" + link.substr(1) + ">" + link + "</a>"
      linkedBio += tag
    }

    document.getElementById("bio").innerHTML = linkedBio

我本来打算使用string.split(" "),但后来我意识到,如果我这样做了,我将销毁特定格式的文本,如果我使用array.join(" ")后,所有的格式更改。

原著:“我为最酷的公司工作:@aws,@microsoft和@apple”。

加入:“我为最酷的公司工作:@aws,微软和苹果”

逗号乱七八糟。

有没有办法把它精简和/或简化呢?JS不是我最强的语言。

EN

回答 1

Code Review用户

回答已采纳

发布于 2019-04-01 22:13:24

您想要的函数是replace

代码语言:javascript
复制
function link_ats(text) { 
    return text.replace( /@(\w+)/g, '@$1' ) 
}

document.getElementById("bio").innerHTML = link_ats("The coolest company to work for is @github!  There is also @aws and @microsoft.", "bio");
票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/216685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档