0

In class="listing" all li a with string "-p." should be replaced to " / p. " eg. "1r-p.1_1" should be converted to "1r / p. 1_1".

current situation:

<ul class="listing">
  <li><a href="#">1r-p.1_1</a></li>
  <li><a href="#">1v-p.1_2</a></li>
  <li><a href="#">2r-p.1_3</a></li>
</ul>

the goal:

<ul class="listing">
  <li><a href="#">1r / p. 1_1</a></li>
  <li><a href="#">1v / p. 1_2</a></li>
  <li><a href="#">2r / p. 1_3</a></li>
</ul>

I tried with the following snippet but it doesn't affect anything.

$(document).ready(function() {
  $("ul.listing a").text().replace(/-p\./, ' / p. ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="listing">
  <li><a href="#">1r-p.1_1</a></li>
  <li><a href="#">1v-p.1_2</a></li>
  <li><a href="#">2r-p.1_3</a></li>
</ul>
Trinity76
  • 665
  • 1
  • 6
  • 20
  • 1
    Have you stepped through the code in a debugger? – KyleMit Mar 15 '18 at 14:42
  • 1
    `replace()` does not update the source. You have to store the changed string back into the place it should go. – Taplar Mar 15 '18 at 14:46
  • 1
    You should be replacing the **text content**, there is no `src` attribute. – Peter B Mar 15 '18 at 14:46
  • Possible duplicate of [How do I replace text inside a div element?](https://stackoverflow.com/questions/121817/how-do-i-replace-text-inside-a-div-element) or [Jquery: Find Text and replace](//stackoverflow.com/q/8146648) – Heretic Monkey Mar 15 '18 at 14:50
  • Possible duplicate of [Jquery: Find Text and replace](https://stackoverflow.com/questions/8146648/jquery-find-text-and-replace) – Asons Mar 15 '18 at 15:03

1 Answers1

4

You want to use the .text() function on the anchors like so:

$(document).ready(function() {
  $("ul.listing a").text(function(i,txt) {
    return txt.replace(/-p\./, ' / p. ');
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="listing">
  <li><a href="#">1r-p.1_1</a></li>
  <li><a href="#">1v-p.1_2</a></li>
  <li><a href="#">2r-p.1_3</a></li>
</ul>
Asons
  • 84,923
  • 12
  • 110
  • 165
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Pretty sure down voter meant that with `text()`, and if their will be html inside the anchor, it get stripped out, with `html()` it will be preserved. – Asons Mar 15 '18 at 14:59
  • what does the argument "i" in the function text(function(i,txt) do exactly? It's not used in the function body. can someone elaborate? – Trinity76 Mar 15 '18 at 20:07
  • 1
    @Trinity76 if you read the docs about the function you'll see that the first argument passed to the function is the index of the element being iterated on. _"function Type: Function( Integer index, String text ) => String"_ – j08691 Mar 15 '18 at 20:24