admin管理员组文章数量:1289506
I have this regular expression that puts all the words that starts with @ into span tags. I've acplished what is needed but i'm not sure that i pletely understand what i did here.
content.replace(/(@\S+)/gi,"<span>$1</span>")
- The () means to match a whole word, right?
- The @ means start with @.
- The \S means "followed by anything until a whitespaces" .
But how e that if don't add the + sign after the \S , it matches only the first letter?
Any input would be appreciated .
I have this regular expression that puts all the words that starts with @ into span tags. I've acplished what is needed but i'm not sure that i pletely understand what i did here.
content.replace(/(@\S+)/gi,"<span>$1</span>")
- The () means to match a whole word, right?
- The @ means start with @.
- The \S means "followed by anything until a whitespaces" .
But how e that if don't add the + sign after the \S , it matches only the first letter?
Any input would be appreciated .
Share Improve this question asked Dec 1, 2013 at 9:10 user3001191user3001191 1- javascriptkit./javatutors/redev2.shtml – user1636522 Commented Dec 1, 2013 at 9:27
5 Answers
Reset to default 6\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
Sharing code to change hashtags into links
var p = $("p");
var string = p.text();
p.html(string.replace(/#(\S+)/gi,'<a href="http://twitter./hashtag/$1">#$1</a>'));
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Test you code here #abc #123 #xyz</p>
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.
/(@\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
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.
本文标签: javascriptRegexreplace all words starting with Stack Overflow
版权声明:本文标题:javascript - Regex, replace all words starting with @ - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741452379a2379559.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论