jQuery match regex jQuery match regex jquery jquery

jQuery match regex


I couldn't tell exactly what you were asking with your question, so here are four possibilities. Hopefully one of these matches what you intended to ask or you can slightly modify one of them to fit.

To select all input items with a class of player-xx where xx is a number, you can do this:

var playerClass = $('input[class^="player-"]').filter(function() {    return((" " + this.className + " ").match(/\splayer-\d+\s/) != null);});

The first jQuery selector gets any class name that starts with "player-". The filter then eliminates any items that aren't also "player-nn".

If you're only trying to examine whether one particular classname contains player-nn, then you can do that like this:

if ((" " + $(this).parent().attr('class') + " ").match(/\splayer-\d+\s/) != null) {    // the parent has player-nn as a class}

If you just want to get the matching class on the parent, you can do that with this:

var matches = (" " + $(this).parent().attr('class') + " ").match(/\s(player-\d+)\s/);if (matches) {    playerClass = matches[1];}

If you're trying to actually get the number after the player-, you can do that like this:

var matches = (" " + $(this).parent().attr('class') + " ").match(/\splayer-(\d+)\s/);if (matches) {    playerNum = parseInt(matches[1], 10);}

Note: All of these examples use a trick (which I learned from jQuery) that if you add a space onto the beginning and end of the overall classname, then you can look for a given classname with a regex by looking for your particular classname surround on both sides by whitespace. This makes sure you don't match a part of a longer classname and only match whole classnames. jQuery uses this trick in it's .hasClass() implementation.


I think this is what you need:

var playerClass = $(this).parent().attr('class').match(/player-\d+/);


To select all input elements that have a class name starting with "player-", you could use this:

var playerClass = $('input[class^="player-"]');

The "starts-with" selector is described here: http://api.jquery.com/attribute-starts-with-selector/

This will not ensure that "player-" is immediately followed by a digit though.