Posts tagged "regular-expressions"

End of string anchor in JavaScript regular expressions

JavaScript's regular expressions are less than awesome, sadly. One limitation is the lack of start of string and end of string anchors. In Perl, for example, \A matches the start of a string, \Z the end.

Most of the time it's possible to get by with ^ and $ which act like \A and \Z except in multiline mode where they match the start and end of any line.

It's possible, though, to have a lookahead act as an end of string anchor in multiline mode:

> /bar(?![\s\S])/m.test('foo\nbar')
true
> /bar(?![\s\S])/m.test('foo\nbar\n')
false
> /bar(?![\s\S])/m.test('foo\nbar\nbaz')
false

(?![\s\S]) at the end of the pattern is equivalent to \Z.

Start of string anchor?

Unfortunately, since JavaScript offers lookahead but not lookbehind, this approach can't be used to simulate \A.

Linkify tweets with regex

Regular expressions are powerful, useful, and — in my opinion — lots of fun! Thanks to the prevalence of Twitter, every web developer will be exposed to regex sooner or later: before outputting tweets in HTML, Twitter names and hyperlinks must be wrapped in anchor tags.

Matching @names

Here's the gist: a match will begin with "@" and the at sign must be followed by one or more word (letter / number / underscore) characters. The @name must either appear at the beginning of the tweet or be preceded by a space. This prevents the regular expression from matching "@example" in "me@example.com".