-1

I have the following script which works:

classes = $(this).attr("class").split('_');

If $(this)'s class was:

class="billed_department_employee_client_code"

The end result would look like this:

["billed", "department", "employee", "client", "code"] 

This is exactly what I want as it allows me to do stuff like this

console.log( classes[0] );
console.log( classes[1] );
console.log( classes[2] );
console.log( classes[3] );

Is it possible to remove a single value from classes and move the rest of the values back?

For example,

if classes contains department, remove it. So, if it looks like this:

["billed", "department", "employee", "client", "code"] 

it should become:

["billed", "employee", "client", "code"] 

How can this be done?

oshirowanen
  • 15,297
  • 82
  • 198
  • 350
  • Of course it's possible. What have you tried? Did you make an attempt to find the answer? –  Jun 06 '12 at 15:06
  • If you know the index then use splice, if you want to search the word, use jQuery's grep. – ayyp Jun 06 '12 at 15:07

3 Answers3

2

You can use the splice() method.

classes.splice(1, 1);

will remove 1 item (second parameter) starting from index 1 (first parameter). If you don't know the index, you can use indexOf() to find it.

Some browsers do not support indexOf() so you can use the script from MDN to use it. You'll also need to check to make sure indexOf() doesn't return -1 (not found) as passing in negative parameter for index into splice() will cause it to remove items from the end of the array.

ZER0
  • 24,846
  • 5
  • 51
  • 54
sachleen
  • 30,730
  • 8
  • 78
  • 73
1

Yes. It can be done. This way:

var c = ["billed", "department", "employee", "client", "code"];
c.splice( c.indexOf('department'), 1); // will remove 'department' from the array.
c.join("_"); // will return "billed_employee_client_code"
Parth Thakkar
  • 5,427
  • 3
  • 25
  • 34
0

You can use splice, and indexOf if you're using a relative modern browser (you can always apply a shim for the rest). So:

var pos = classes.indexOf("department");

if (pos > -1) {
    classes.splice(pos, 1);
}

$(this).attr("class", classes.join("_"));
ZER0
  • 24,846
  • 5
  • 51
  • 54
  • Will splice and indexOf work on IE8? – oshirowanen Jun 06 '12 at 15:32
  • @oshirowanen `splice` will work but unfortunately IE8 is not considered a "modern browser", so you have to apply a shim for `indexOf` as described in the related link. If you're using jQuery you could use [inArray](http://api.jquery.com/jQuery.inArray/) instead, or if you're using underscore you have an [indexOf](http://underscorejs.org/#indexOf) implementation. – ZER0 Jun 06 '12 at 15:35