Delmon Young
Delmon Young

Reputation: 2053

jQuery - Using multiple .replace methods

I've got a div that will swap the position of the class name depending on where it is on the page. I'm trying to strip the header-section- text and header-type text so I just have payment or resource. But depending on where the class is I will sometimes get a space before or after the header-type class. In order to do this I'm calling .replace() 3 times there has to be a better more concise way of doing this instead of having three .replace methods. Any ideas?

 <div class="header-section-payment header-type"></div>
 <div class="header-type header-section-resource"></div>

JQUERY

   var headerCategory = $(this).closest('div[class*="header-section-"]')
   .attr('class')
   .replace('header-section-', '')
   .replace(' header-type', '')
   .replace('header-type ', '');

I learn best by code samples so please include where applicable. Thanks!

Upvotes: 0

Views: 45

Answers (1)

jfriend00
jfriend00

Reputation: 707466

First off an extra space in the class name does absolutely no harm. Maybe if you were doing the same operation thousands of times you might worry about an accumulation of extra spaces, but it doesn't really cause a problem in any way.

For your particular situation, you can use jQuery's .removeClass("header-type") for that class name and then you won't have extra blanks to worry about when you just remove "header-section". That could work like this:

var headerCategory = $(this).closest('div[class*="header-section-"]')
   .removeClass("header-type")
   .each(function() {
        this.className = this.className.replace('header-section-', '');
    }); 

Please note that in your existing code, you are calling .replace(), but not assigning the result to anything and your code would not work if headerCategory had more than one DOM object in it either which is why I use .each() here.

Upvotes: 1

Related Questions