Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change part of name with Javascript and jQuery

I have a few select elements on my page and i want to remove a part of the name.

Their name look something like this:

ctl02$fieldname

The part that i want to remove is: ctl02$. So that it leaves me with fieldname only.

That part that i want to remove always starts with ctl then a two digit number ending with a $.

I tried it with the following code, but that didn't do the trick:

$(".elements select").each(function() {
    this.setAttribute("name", this.getAttribute("name").replace(/ctl([0-9]+)\$$/, ""));
});

Anyone any idea how i can do this?

Here's a demo: http://tinkerbin.com/Klvx5qQF

like image 581
Vivendi Avatar asked Dec 20 '25 09:12

Vivendi


2 Answers

Just an error in the regex. I don't know why you doubled the $, a $ at the end of a regex has a specific meaning that isn't what you want.

Here's the fixed version :

$(".elements select").each(function() {
    this.setAttribute("name", this.getAttribute("name").
       replace(/ctl[0-9]+\$/, ""));
});

You don't need to capture anything, that's why I also removed the parenthesis.

If you want to be sure to remove the ctl thing only when it's at the start of the name, you may change the regex to /^ctl[0-9]+\$/.

like image 136
Denys Séguret Avatar answered Dec 23 '25 00:12

Denys Séguret


I guess there is no need in regex here:

$(".elements select").attr("name", function(i, attr) {
    return attr.substring(attr.indexOf("$") + 1);
});
like image 37
VisioN Avatar answered Dec 22 '25 23:12

VisioN



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!