一个用户写了一个问题,询问是否在bio (或任意标记)中,任何有标记的帐户都可以自动链接,就像在Github上一样。
我给了他们这个功能:
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不是我最强的语言。
发布于 2019-04-01 22:13:24
您想要的函数是replace:
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");https://codereview.stackexchange.com/questions/216685
复制相似问题