Vivendi
Vivendi

Reputation: 21007

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

Upvotes: 3

Views: 81

Answers (3)

sourcecode
sourcecode

Reputation: 1802

use this :

$(function() {
    $("select").each(function() {
        var name = $(this).attr("name");

        $(this).attr("name", name.replace(/(ctl[0-9]+)/g, ""));

    });
});

see demo : link

Upvotes: 0

VisioN
VisioN

Reputation: 145388

I guess there is no need in regex here:

$(".elements select").attr("name", function(i, attr) {
    return attr.substring(attr.indexOf("$") + 1);
});

Upvotes: 4

Denys Séguret
Denys Séguret

Reputation: 382122

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]+\$/.

Upvotes: 4

Related Questions