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.
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.
i is unnecessary, but won't affect anything.
/(@\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
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>
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.
©2020 All rights reserved.