Modify all ids that contain certain text within their name

0

I have a table where each of your td elements have an id in this format:

<td id="random123random"></td>

where "random" can be anything (albeit of the same length) and the only thing that certain ids have in common is the number "123" in the middle.

What I need is to select all the td that contain that 123 of the medium to change it to a "456".

I suppose that in JQuery there should be a way to create a selector that does what I want, with the aim of having something like:

(a modo demostrativo) nueva = "idQueConserveEltextoDeLosExtremosperoCambie123por456"
$("idQueContenga123enElmedio").attr("id", nueva);

So now that I see it, it's difficult for me to fix the new ids, because when they are reassigned to each td, they must keep the random text of the extremes and only change the number "123" in the middle for a "456" .

Thanks for your time.

EDIT

Sorry if I expressed myself wrong, but when I said "select all the ids that ..." I was not referring to any type of database query, they are simply the ids of the table that I mentioned at the beginning, they are ids that they are being worked with jquery only in the frontend.

    
asked by Roberto Sepúlveda Bravo 18.10.2016 в 00:38
source

3 answers

2

As I mentioned @Leandro use *= to implement a Like and to change the id you would do it by means of the function replace

$('tr [id*="123"]').attr('id', function(_, id) {
   return id.replace('123', '456');
});

According to the documentation Pass function to attr

    
answered by 18.10.2016 / 01:04
source
1

If you use jquery to select items by *=

Attribute Contains Selector [name *="value"]

you could select by applying a like in the search

$("[Id*='123']").each(function(){

   $(this).attr('id', 'valor');

});

.each ()

    
answered by 18.10.2016 в 00:51
1

You can use the filter () method to find specific IDs thanks to a regular expression, in the following way:

var match = $('td').filter(function(){
    return this.id.match(/123/);
  });

Where 123 is what you want to find, and then modify it as mentioned above with jQuery .each:

match.each(function(){
    $(this).attr('id','test');
  });

If you want to keep the ends of each string, and you know that the ID will always be numeric you can save it in the .each () function with another regular expression in which you save in an Array everything that is not numeric (assuming that the ID will always be a number):

match.each(function(){
    var prev = $(this).attr('id').match(/[^0-9]{2,}/g);
    var concat = prev[0] + 999 + prev[1];
    console.log("concat: " + concat);
    $(this).attr('id',concat);
  });

I made an example here link

    
answered by 18.10.2016 в 03:00