正则表达式用链接替换主题标签

时间:2019-04-22 10:42:40

标签: javascript

我检查了其他主题,但是找不到我的问题的明确答案。 我正在制作一个标签系统,但是使用了javascript 所以我做了我的正则表达式并测试了它,这是正确的,所以现在我正尝试用链接替换主题标签词,因此我需要您的帮助,如何将匹配的词放在链接中带#的链接中,而在链接href中没有#的

      var regex1 = /#+([a-zA-Z0-9_]+)/ig;
      var strin = "hello this is a test. #hello #hashtags #one #two";
                    var result1 = strin.match(regex1);

                    if(result1 !== null) {


                        strin = strin.replace(regex1,"<a href='search.php?sec=all&q="+wordsHere+"' class='hashtag_link' target='_blank'>"+hashtagWordHere+"</a>");

                    }

1 个答案:

答案 0 :(得分:3)

替换第二个参数可以是一个函数,其中第一个参数是匹配的值,因此使用此值,您可以构建字符串。像这样的东西。

const regex = /#+([a-zA-Z0-9_]+)/ig;
const text = "hello this is a test. #hello #hashtags #one #two";
const replaced = text.replace(regex, value => `<a href='search.php?sec=all&q=${value.substring(1)}' class='hashtag_link' target='_blank'>${value}</a>`);

console.log(replaced);

const regex = /#+([a-zA-Z0-9_]+)/ig;
const text = "hello this is a test. #hello #hashtags #one #two";
const replaced = text.replace(regex, function(value) {
  return (
    "<a href='search.php?sec=all&q="+value.substring(1)+"' class='hashtag_link' target='_blank'>"+value+"</a>"
  )
});

console.log(replaced);