lee
lee

Reputation: 239

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

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

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

Upvotes: 4

Views: 2818

Answers (2)

Dhara Parmar
Dhara Parmar

Reputation: 8101

It will replace all , with 'a' character. use of the "g" within this - that stands for "global" and causes the replacing of all of the target characters in the string - without it you just replace the first instance as you have discovered. try it.

string.replace(/\,/g, 'a');

Upvotes: 3

Pranav C Balan
Pranav C Balan

Reputation: 115222

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

$('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>
<div>
  <a href="#">text1</a>, <a href="#">text2</a>, <a href="#">text3</a>,
</div>

Upvotes: 3

Related Questions