Change part of the name using Javascript and jQuery

I have several elements select

on my page and I want to remove part of the name.

Their name looks something like this:

ctl02$fieldname

      

The part that I want to delete: ctl02$

. So this leaves me with only fieldname

.

This part that I want to remove always starts with ctl

, then a two-digit number ending in $

.

I tried it with the following code, but it didn't help:

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

      

Does anyone know how I can do this?

Here is a demo: http://tinkerbin.com/Klvx5qQF

+3


source to share


3 answers


Just a mistake in the regular expression. I don't know why you doubled $

, a $

at the end of the regex has a specific meaning that doesn't suit you.

Here's the fixed version:

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

      



You don't need to grab anything, so I removed the brackets as well.

If you want to remove the ctl-thing only at the beginning of the name, you can change the regex to /^ctl[0-9]+\$/

.

+4


source


I think there is no need for regex here:



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

      

+4


source


use this:

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

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

    });
});

      

see demo: link

0


source







All Articles