lee lee - 1 year ago 102
Javascript Question

replace all specific character inside div with jquery

I'm trying to replace all the commas (",") inside the div with a character. I've tried googling and it seems .replace() replaces only the first comma and it removes the links from the


How do I replace all the commas with another character inside the div without it removing the links, using jquery?

<a href="#">text1</a>, <a href="#">text2</a>, <a href="#">text3</a>, <a href="#">text4</a>,

Answer Source

Get all text node inside the div and update it, that will be the better way than updating entire html inside div.

  .contents() // get all child nodes
  .each(function() { // iterate over them
    if (this.nodeType == 3) // check node type is text
      this.textContent = this.textContent.replace(/,/g, '+'); // update text content if it's text node
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <a href="#">text1</a>, <a href="#">text2</a>, <a href="#">text3</a>,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download