0

http://jsfiddle.net/cYmxB/

$('.change').click(function() {
    $('.link').each(function(e) {
        var color = this.className.match(/color-\w+/gi);
        alert(color);
    });
});​

I'd basically like this to alert the regular expression found with \w+ rather than the entire string. How can I do this?

Additionally, how can I remove color- without removing the regular expression after this instance?

2 Answers 2

1

You can use the javascript regular expressions to loop though the matches which will return the groups in an array. You can also use the replace function with a group back reference to remove the color-

$('.change').click(function() {
    $('.link').each(function(e) {
        // find regex matching groups
        var regex = /color-(\w+)/gi;
        var match;
        while (match = regex.exec(this.className)) {
            alert(match[1]);
        }
        // remove color-
        this.className = this.className.replace(/color-(\w+)/gi, "$1");
    });
});

http://jsfiddle.net/cYmxB/2/

Sign up to request clarification or add additional context in comments.

Comments

1

Use a capturing group for the color:

$('.change').click(function() {
    $('.link').each(function(e) {
        var pattern = /color-(\w+)/gi;
        var match = pattern.exec(this.className);
        var color = match[1];
        alert(color);
    });
});​

http://jsfiddle.net/cYmxB/1/

Comments

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.