Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: replace() class name / regex

Tags:

jquery

regex

I am trying to write line of jquery that finds an input that has a class that begins with "a\d" (the letter a and a number) and replace the number with another number.

This is what I have tried, does anyone notice why this would not work?

$('form').find('input[class^="a\d"]').replace(/a\d+/,'a22');

Please note: this is one line out of many, I have extracted this line because it is where I am having trouble.

like image 952
superUntitled Avatar asked Dec 04 '25 08:12

superUntitled


1 Answers

You'll need to do it more like this:

$('form').find('input[class^="a"]').attr('class', function(i,cls) {
    if( /a\d/.test( cls ) ) {
        return cls.replace(/a\d+/,'a22');
    }
});

When using .attr() to set the class (or any attribute), you can pass it a function which has 2 parameters. The i is the current index in the iteration. The cls is the current value of class.

The return value will be used to update the class. If nothing is returned, nothing will be changed.

like image 108
user113716 Avatar answered Dec 05 '25 23:12

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!