juan
juan

Reputation: 81894

String manipulation in jQuery

I have a div which collapses clicking on a text header. I want to change the header from "+ filters" to "- filters" accordingly (when the div is collapsed or expanded)

How can I perform this with jQuery?

if (headerDiv.text() starts with "+")
    replace "+" with "-" 
else 
    replace "-" with "+"

Upvotes: 6

Views: 25692

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 1403

keep it simple, why do you need to parse it out? your just replacing one string with another.

if(headerDiv.text() == '+ filters')
{
    headerDiv.text() == '- filters';
}
elseif(headerDiv.text() == '- filters')
{
    headerDiv.text() == '+ filters';
}

Upvotes: 1

fmsf
fmsf

Reputation: 37137

I would do:

var plus_string = "<span class=/"plus/">+</span>";
var minus_string = "<span class=/"minus/">-</span>";


if($("div.header").hasClass("plus")){
    $("div.header").removeClass("plus");
    $("div.header").addClass("minus");
    $("div.header").append(plus_string);
    $("span.plus").remove();
 } else (... the reverse of the above...)

This because i would use the class plus and minus to handle a bit of css to change the appearance of the header div. As you're probably already doing that, you can play a bit with it like this :)

Upvotes: 4

juan
juan

Reputation: 81894

Never mind, I figured it out

if ($(header).text().trim().charAt(0) == "+")
    $(header).text($(header).text().replace("+", "-"));
else
    $(header).text($(header).text().replace("-", "+"));

If this is not the correct way, I'd appreciate a heads up

Upvotes: 13

Related Questions