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.

content.replace(/(@\S+)/gi,"<span>$1</span>")

  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 .

Answers:

Answer

\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

Answer
content.replace(/(@\S+)/gi,"<span>$1</span>")

(@\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.

Answer
/(@\S+)gi/

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
Answer

Sharing code to change hashtags into links

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

p.html(string.replace(/#(\S+)/gi,'<a href="http://twitter.com/hashtag/$1">#$1</a>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Test you code here  #abc #123 #xyz</p>

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.