使用正则表达式替换以@开头的子字符串

时间:2018-11-30 23:28:21

标签: javascript regex string

我是正则表达式的新手,已经花了几个小时来解决这个问题

let text = "My twitter handle is @emmy, I follow @jo and @pe"

我需要用<a href="https://twitter.com/emmy">@emmy</a>替换@emmy,同样,字符串中其他以@开头的其他字符串。

这是我通过搜索互联网并阅读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推荐了最好的学生,并竭诚为人 致力于

任何对解决方案的投入将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果要使用replace并指定一个function作为第二个参数,则可以使用3个捕获组来捕获@@本身和名字。

在函数中添加3个与捕获组相对应的参数,然后可以在替换中使用这些参数:

(^|\W)(@)(\w+)(?!\w)

Regex demo

let text = "My twitter handle is @emmy, I follow @jo and @pe";

function linkify(text) {
  let regex = /(^|\W)(@)(\w+)(?!\w)/g;
  return text.replace(regex, function(handle, p1, p2, p3) {
    return `${p1}<a href="https://twitter.com/${p3}>${p2}${p3}</a>`;
  });
};

console.log(linkify(text));

答案 1 :(得分:1)

我认为您不需要针对此问题的回调,直接替换应该可以:

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>'));