Q:

javascript how to regex match and replace on hashtags but exclude the hashtag character

I have the following function:
function formattedTitle(posttitle,hreflink) {
  return `<a href='`+ hreflink +`'>` + posttitle.replace(/(^|\s)(#[-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>$2</a><a href='`+ hreflink + `'>`) + '</a>';
}

When I run 
console.log(formattedTitle('This is #awesome news','google.com'));

It outputs:
<a href='google.com'>This is </a><a class="hashtag" href='/search?q=hashtag:"#awesome"'>#awesome</a><a href='google.com'> news</a>

function formattedTitle(posttitle, hreflink) {
  return `<a href='` + hreflink + `'>` + posttitle.replace(/(^|\s)(#[-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>$2</a><a href='` + hreflink + `'>`) + '</a>';
}


console.log(formattedTitle('This is #awesome news', 'google.com'));

Notice how it includes the "#" in the $2 match. How can I exclude the hashtag character in the hashtag: attribute but keep it in between the href value?
So the output should look like:
<a href='google.com'>This is </a><a class="hashtag" href='/search?q=hashtag:"awesome"'>#awesome</a><a href='google.com'> news</a>

I have been able to get it to work by doing another replace on the entire thing to replace '/search?q=hashtag:"# with '/search?q=hashtag:" but I am wondering if it's possible without the second replace?

A:

Move the # outside of the captured 2nd group, so it isn't captured. When replacing, in the href, replace with just $2 (so no hashtag). When replacing the text inside the <a>, replace with #$2, so that the hashtag gets added in the proper place:

function formattedTitle(posttitle, hreflink) {
  return `<a href='` + hreflink + `'>`
    + posttitle.replace(/(^|\s)#([-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>#$2</a><a href='` + hreflink + `'>`)
    + '</a>';
}

console.log(formattedTitle('This is #awesome news', 'google.com'));

