Michel Ayres
Michel Ayres

Reputation: 5985

Explanation of this Regular expression

I'm not very good with Regular Expressions, and I didn't fully understood this one, All I get from this is that it find every h1 and add a class to it's last word.

$("h1").html(function(index, old) {
    return old.replace(/(\b\w+)$/, '<span class="myClass">$1</span>');
});

I'm trying to make it work by last two characters

Upvotes: 1

Views: 54

Answers (2)

georg
georg

Reputation: 214949

This (poorly written) regex finds a sequence of word characters (latin letters, numbers and underscore) at the end of the input. The same can be achieved much simpler: /\w+$/, so neither \b nor parens are actually necessary here.

To match two last words you'll need something like

/\w+(?=(\W+\w+)?$)/g

which means "a word, optionally followed by another word before the end of the input".

To match two last characters -- well, this is something you should be able to figure out on your own (hint: any character is . (dot) in regex language).

Upvotes: 2

Toto
Toto

Reputation: 91385

Here is and explanation:

/       : regex delimter
  (     : begin capture group #1
    \b  : word boundary
    \w+ : one or more word character (same as [a-zA-Z0-9_]+)
  )     : end of group
  $     : end of string
/       : regex delimiter

It matches the last word of the string, ie the last word of the h1 tag.

Upvotes: 5

Related Questions