Get the FIRST CHAR of matched substring

40 views Asked by At

I'm trying to insert into link (href) a matched substring but without the first char who are a '#'.

Infact I would like wrapp #hashtag with a link, that's working very good but when I using $& pattern, it return me the matched on the whole. I want take off the '#' in my href.

.replace(/#[a-z0-1A-Z]+/g, '<a href="https://twitter.com/search?q=**$&**">$&</a>');

It's possible to exclude the first char ?

2

There are 2 answers

1
Sabuj Hassan On

Use group capture. And the capture will be at $1

.replace(/#([a-z0-1A-Z]+)/g, '<a href="https://twitter.com/search?q=**$1**">$&</a>');
3
Linus Unnebäck On
.replace(/#([a-z0-1A-Z]+)/g, '<a href="https://twitter.com/search?q=$1">$&</a>');

Placing part of the regex inside parentheses (called group capturing) makes that part accessible with $1, $2, $3 and so on for each set of parentheses.