JQuery: replace () class name / regex

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

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

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

Please note: this is one line out of many, I extracted this line because I am having problems.

+3
source share
2 answers

You will need to do it something like this:

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

When used .attr()for installation class(or any attribute), you can pass it a function that has 2 parameters. i- current index in iteration. cls- current value class.

return class. , .

+10

var regExp = /(a\d+)(.*)?/;
$('form').find('input[class^="a"]').each(
    function()
    {
        var el = this;
        var className = el.replace(regExp, "a22$2");
        el.className = className;
    }
);
0

Source: https://habr.com/ru/post/1783676/


All Articles