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>")

  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 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>")

  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 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
Add a ment  | 

5 Answers 5

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