0

I'm browsing through the code for twitter bootstrap and I've coma across this snippet a few times.

href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7

Regexes are my blindspot and I can't figure out most of them. What is it replacing? Is it whitespace after the #?

Side note. Can anyone recommend a good source for regex tuition?

1

1 Answer 1

6

Here's what it's looking for:

.*     # any number of characters (optional)
(?=    # open a lookahead
#      # find a hash tag
[^\s]+ # at least one non-whitespace character
$      # end of line
)      # close the lookahead

So, for example, it matches what comes before a hash tag:

replace this!#foobar   <-- matches: replace this!
hello world#goodbye    <-- matches: hello world
no match here !        <-- doesn't match anything because there is no hash
what?#                 <-- does not match because there is nothing after the hash
what?# asd             <-- does not match because there is a whitespace-character
Sign up to request clarification or add additional context in comments.

6 Comments

a few examples of valid and invalid matches would go nicely with that answer ;)
@alan: Absolutely brilliant! This is the kind of clear answer I was hoping for.
@JamesSouth to be exact: it matches #foobar and #goodbye, not replace this! and hello world. It doesn't match #f oobar or # though.
@Christoph: No. The hash and everything after it is enclosed in a positive lookahead, which does not participate in the match. The only thing that matches the regex is what is before the lookahead.
sry, i confused the word match. what i really ment: the replace returns you the #foobar and #goodbye because it matches the rest of the string and replaces it with ''. Some kind of double negation... My fault;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.