Rob
Rob

Reputation: 199

How can I replace a substring of text within an anchor tag on click?

I have a tag:

<a class="showrepbut" href="javascript:void(0);" data-fpost="[email protected]">Hide 2 replies</a>

and I would like to do something like this:

$('.showrepbut').click(function () {
   if ($(this).text().includes('Show')) {
       $(this).replace(/Show/g, 'Hide');
   }
   else if ($(this).text().includes('Hide')) {
       $(this).replace(/Hide/g, 'Show');
   }
});

So that the show is replaced with hide when show is present and visa versa. Obviously the above doesn't work. I've tried .includes, :contains .innerHTML.indexOf etc and nothing seems to work.

JSFiddle here

Can anyone clarify how I should approach this correctly?

Upvotes: 2

Views: 273

Answers (5)

Marco Salerno
Marco Salerno

Reputation: 5203

It works like that ^^

$('.showrepbut').click(function () {
    if ($(this).text().includes('Show')) {
        $(this).text($(this).text().replace('Show', 'Hide'));
    }
    else if ($(this).text().includes('Hide')) {
        $(this).text($(this).text().replace('Hide', 'Show'));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a class="showrepbut" href="javascript:void(0);" data-fpost="[email protected]">Hide 2 replies</a>

Upvotes: 1

Manish Patel
Manish Patel

Reputation: 3674

Try this:

$('.showrepbut').click(function () {
  var text = $(this).text();
  if ($(this).text().includes('Show')) {
    $(this).text(text.replace(/Show/g, 'Hide'));
  }
  else if ($(this).text().includes('Hide')) {
    $(this).text(text.replace(/Hide/g, 'Show'));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<a class="showrepbut" href="javascript:void(0);" data-fpost="[email protected]">Hide 2 replies</a>

Upvotes: 1

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

You need to replace $(this).text() instead of $(this).

 $('.showrepbut').click(function () {
            if ($(this).text().includes('Show')) {
                $(this).text($(this).text().replace(/Show/g, 'Hide'));
            }
            else if ($(this).text().includes('Hide')) {
                $(this).text($(this).text().replace(/Hide/g, 'Show'));
            }
        });

Upvotes: 4

Suresh Atta
Suresh Atta

Reputation: 121998

This should do

$('.showrepbut').click(function () {                        
            var txt = $(this).text().indexOf("Show")> -1 ? "Hide" : "Show";
            $(this).text(txt+ "2 replies");
 });

https://jsfiddle.net/hshzp4rb/5/

Upvotes: 1

Super User
Super User

Reputation: 9642

You can fine updated code below:

$('.showrepbut').click(function () {
    if ($(this).text().includes('Show')) {
        $(this).html($(this).text().replace(/Show/g, 'Hide'));
    }
    else if ($(this).text().includes('Hide')) {
        $(this).html($(this).text().replace(/Hide/g, 'Show'));
    }
});

for working fiddle demo click here

Upvotes: 1

Related Questions