简体   繁体   中英

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. 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. Here's a JSFiddle with what I have so far. 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.

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.

JSFiddle Demo

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

Here is a method using pure 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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