我是正则表达式的新手,我已经绞尽脑汁几个小时来解决这个问题
let text = "My twitter handle is @emmy, I follow @jo and @pe"
我需要将 @emmy 替换为 <a href="https://twitter.com/emmy">@emmy</a>
,同样,字符串中以 @ 开头的任何其他字符串。
这是我通过搜索互联网和阅读 docs on MDN 得出的结论。
function linkify(text) {
let regex = /(?:^|\W)@(\w+)(?!\w)/g;
return text.replace(regex, function(handle) {
return `<a href="https://twitter.com/${handle.slice(1)}>${handle}</a>`;
})
}
此解决方案的问题在于,有时它会省略一些文本,例如本周早些时候,@emmy 精选了最好的学生并致力于 早些时候周,
任何有关解决方案的意见都将不胜感激。
最佳答案
我认为您不需要回调来解决此问题,直接替换应该可以:
let text = "My twitter handle is @emmy, I follow @jo and @pe";
console.log(text.replace(/(^|\W)@(\w+)\b/g, '$1<a href="https://twitter.com/$2">@$2</a>'));
关于javascript - 使用正则表达式替换以 @ 开头的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566267/