Regex, replace all words starting with @

I have this regular expression that puts all the words that starts with @ into span tags. I've accomplished what is needed but i'm not sure that i completely understand what i did here.


  1. The () means to match a whole word, right?
  2. The @ means start with @.
  3. The \S means "followed by anything until a whitespaces" .

But how come that if don't add the + sign after the \S , it matches only the first letter?

Any input would be appreciated .



\S is any non-whitespace character and a+ means one or more of a. So

@\S -> An @ followed by one non-whitespace character.

@\S+ -> An @ followed by one or more non-whitespace characters


(@\S+) is a capturing group which captures @ followed by 1 or more (+ means 1 or more) non-whitespace characters (\S is a non-whitespace character)

g means global, ie replace all instances, not just the first match
i means case insensitive
$1 fetches what was captured by the first capturing group.

So, the i is unnecessary, but won't affect anything.


1st Capturing group (@\S+)
    @ matches the character @ literally
    \S+ match any non-white space character [^\r\n\t\f ]
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
g - all the matches not just first
i - case insensitive match

Sharing code to change hashtags into links

var p = $("p");
var string = p.text();

p.html(string.replace(/#(\S+)/gi,'<a href="$1">#$1</a>'));
<script src=""></script>
<p>Test you code here  #abc #123 #xyz</p>


The \S means "followed by anything until a whitespaces" .

That's not what \S means. It's "any character that's not a whitespace", that is, one character that's not a whitespace.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.