JS:无法将所有链接包装到<a>标记中

时间:2019-07-02 10:12:29

标签: javascript regex

我正在尝试使用以下简单的JS代码将字符串中的所有链接包装到<a>标记中:

var str = 'Foo https://example1.com bar foo https://www.example2.com bar https://example3.com/url';

var str = str.replace(/(.+)?(http|https)\:\/\/(\S+)(.+)?/g, '$1<a href="$2://$3" target="_blank" rel="nofollow">$2://$3</a>$4');

console.log(str);

但是只有最后一个链接被包裹

如何包装所有链接?

ps。我知道PHP中的解决方案,但是在这里不起作用

4 个答案:

答案 0 :(得分:1)

您无需捕获URL前后的所有内容。替换只会替换已匹配的部分。

var str = 'Foo https://example1.com bar foo https://www.example2.com bar https://example3.com/url';

var str = str.replace(/(http|https)\:\/\/(\S+)/g, '<a href="$1://$2" target="_blank" rel="nofollow">$1://$2</a>');

document.write(str);

答案 1 :(得分:1)

以下是我用来格式化文本的一组功能:

/**
 * Adds anchor elements to all the links inside a string
 * @param {string} text text to be converted
 * @returns {string} converted text 
 */
function setLinks(text) {
  var regex = /(https?:[/]{0,2}|[w]{3}[.])[^ "'>]{1,}/g;
  text = text.replace(/</g, "&lt;");
  text = text.replace(/>/g, "&gt;");
  return text.replace(regex, addLink);
}

/**
 * Surrounds string in an anchor tag
 * @param {string} link url of link
 * @returns {string} 
 */
function addLink(link) {
  var descr = String(link).replace(/^(https?:[/]{0,2})?([w]{3}[.])?/, "www.");
  if (!/^https?:[/]{2}/.test(link)) link = `http://${link}`;
  return `<a href=${link} target="_blank">${descr}</a>`;
}

document.write(setLinks('Foo https://example1.com bar foo https://www.example2.com bar https://example3.com/url'));

答案 2 :(得分:1)

尝试使用$& (完全匹配)

Regex Demo

var str = 'Foo https://example1.com bar foo https://www.example2.com bar https://example3.com/url';

var str = str.replace(/\bhttps?:\/\/\S+/gi, '<a href="$&" target="_blank" rel="nofollow">$&</a>');

document.body.innerHTML = str;

答案 3 :(得分:-1)

在替换时,您不需要处理其他不匹配的零件。

var str = 'Foo https://example1.com bar foo https://www.example2.com bar https://example3.com/url';

var str = str.replace(/(http|https)\:\/\/(\S+)/g, '<a href="$&" target="_blank" rel="nofollow">$&</a>');

console.log(str);