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>

5
  • 1
    Have you stepped through the code in a debugger? Commented Mar 15, 2018 at 14:42
  • 1
    replace() does not update the source. You have to store the changed string back into the place it should go. Commented Mar 15, 2018 at 14:46
  • 1
    You should be replacing the text content, there is no src attribute. Commented Mar 15, 2018 at 14:46
  • Possible duplicate of How do I replace text inside a div element? or Jquery: Find Text and replace Commented Mar 15, 2018 at 14:50
  • Possible duplicate of Jquery: Find Text and replace Commented Mar 15, 2018 at 15:03

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.