简体   繁体   English

使用JavaScript在链接中包装多个主题标签

[英]Using JavaScript to wrap multiple hashtags in links

I'm banging my head against the wall with this, after a good few hours of Googling, searching Stack Exchange and trial and error I haven't been able to figure it out. 经过数小时的谷歌搜索,搜索Stack Exchange以及反复试验后,我无法解决这个问题。 Any help would be hugely appreciated! 任何帮助将不胜感激!

I'm trying to replace hashtags in a paragraphs with links. 我正在尝试用链接替换段落中的主题标签。 I've been able to do this by using the following: 我已经可以使用以下方法做到这一点:

var str = $('.item p').html(),
  regex = /(?:\s|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|$)/gi;

function replacer(){
  var replacementString = $.trim(str.match( regex )[0]);
  return ' <a href="https://www.example.com/'+ replacementString +'" target="_blank">' + replacementString + '</a>';
}
$('.item p').html( str.replace( regex , replacer ) );

This replaces the hashtags successfully but as I'm using [0] then if there are multiple hashtags then it only replaces hashtag with the text of the first one. 这将成功替换井号,但是当我使用[0]时,如果存在多个井号,则仅将井号替换为第一个井号。 Here's a JSFiddle with what I have so far. 这是到目前为止我拥有的JSFiddle I need to try to figure out how to replace each hashtag with a link to that particular hashtag. 我需要尝试弄清楚如何用指向该特定主题标签的链接替换每个主题标签。

I'm not sure whether I should be using a loop and incrementing the [0] or whether I'm going in completely the wrong direction here and there's an easier way to do this. 我不确定是否应该使用循环并递增[0],还是在这里完全朝错误的方向前进,还有一种更简单的方法可以做到这一点。

If anyone has any pointers than I'd really appreciate it! 如果有人比我有任何指针,我将不胜感激!

John 约翰

A simple change like this on your function will do what you want: 在您的函数上进行如下简单更改即可完成您想要的操作:

function replacer(hash){
  var replacementString = $.trim(hash);
  return ' <a href="https://www.example.com/'+ replacementString +'" target="_blank">' + replacementString + '</a>';
}

In you case, there's no need to do a match inside the replacer function invoked by .replace , as the first parameter of that function is already the current matched substring. 在您的情况下,无需在.replace调用的replacer函数内进行匹配,因为该函数的第一个参数已经是当前匹配的子字符串。

JSFiddle Demo JSFiddle演示

EDIT: If you want to match hashtags without spaces in between, you can modify your regex a little: 编辑:如果要匹配标签标签之间没有空格,则可以稍微修改一下正则表达式:

(?:|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|#|$)

UPDATED JSFiddle Demo 更新的JSFiddle演示

Here is a method using pure javascript: 这是使用纯JavaScript的方法:

String.prototype.parseHashtag = function() {
    return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
        var tag = t.replace("#","")
        return '<a href="https://www.example.com/'+ tag + '" target="_blank">' + tag + '</a>';
    });
};

var input = "some randomg string #something some text";

console.log(input.parseHashtag()); // some randomg string <a href="https://www.example.com/something" target="_blank">something</a> some text

See jsFiddle jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM