2

I use a script that adds a dynamic data attribute value from the elements classname - the second part is that I want to trim the value in the data attribute.

Examples of the html:

<div class="newgroup HardDrivesExternal" data-item-tags="newgroup HardDrivesExternal show"></div>

<div class="newgroup ServiceSuppor" data-item-tags="newgroup ServiceSupport"></div>

I want it to look like this:

 <div class="newgroup HardDrivesExternal" data-item-tags="HardDrivesExternal"></div>

<div class="newgroup ServiceSuppor" data-item-tags="ServiceSupport"></div>

In the example I want to remove the first and third word in the data value - I cant remove it from the elements class so I need to do this from the data attribute. Also - the middle word changes dynamically so I want to target the specific words - newgroup and show. To make it worse the word show wont always be a value.

Whats the best way to replace that specific part of the value?

Jerry Svensson
  • 277
  • 1
  • 3
  • 18

2 Answers2

2

As I have commented, you can use split to get array of words and use array.splice() to get second word.

Note: I have used .attr to set because .data(key, val) was not working. Related post. Also I have updated text of element, to show value.

(function() {
  $.each($(".newgroup"), function(i, el){
    var attr = "item-tags";
    var val = $(el).data(attr).split(" ").splice(1,1)[0];
    $(el).attr("data-" + attr, val);
  })
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="newgroup HardDrivesExternal" data-item-tags="newgroup HardDrivesExternal show">test1 </div>

<div class="newgroup ServiceSuppor" data-item-tags="newgroup ServiceSupport"> test2</div>
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

You can use split()

$(document).ready(function() {
    var data = $('.HardDrivesExternal').attr('data-item-tags');
    var newdata = data.split(" ");
    newdata.shift();
    newdata.shift();
    alert(newdata.join(" "));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="newgroup HardDrivesExternal" data-item-tags="newgroup ServiceSupport show anotherTag"></div>
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69