Drew Peer
Drew Peer

Reputation: 377

How do I replace spaces with a comma and then a space in jquery?

I'm copying some html into a textarea and trying to format the current textarea from having a div h3, and h3, <ul> and <li> tags.

// the part being copied and outputs in the textarea like this
<div class="comment" id="comment-11">
     <h3>Comments:</h3>
      <ul>
        <li>comment1</li>
         <li>comment2</li>
      </ul>
</div>

My code:

   $(".approve-group").click(function(){
       let id = this.id;
       let num = id.replace(/[^\d]+/, ''); // get the number only
       let comment = $("#comment-"+num).html();
       comment = comment.trim();

       // I'm trying to strip out all the html and make the comment read comment 1, comment 2 and this is the worst part of my code probably where the bug lies.
       comment = comment.replace('Comments:','');
       comment = comment.replace("<h3></h3>","");
       comment = comment.replace("<ul>","");
       comment = comment.replace("</ul>","");
       comment = comment.replace("</li>",",");
       comment = comment.replace("<li>","");
       comment = comment.replace(/ /g, ', '); // this is where the error is.

       $("#loc-comment").val(comment); //copies to my textarea



    }); 

I'm trying to get it to read

output: comment1, comment2

I've tried this but it doesn't work.

string = string.replace(/ /g,', ');

Error Uncaught Error: Syntax error, unrecognized expression: ,

Thanks guys

Upvotes: 0

Views: 134

Answers (3)

jirassimok
jirassimok

Reputation: 4253

If you don't include let in front of the second expression, it should work as-is. You can't declare a variable with let (or var) twice.

Upvotes: 3

EGC
EGC

Reputation: 1779

I tested this code and it appears to work perfectly fine!

var string = "blah blah blah";
var formattedString = string.replace(/ /g, ', ');

Upvotes: 0

Rob
Rob

Reputation: 10248

Try:

string = string.replace(/\s/g, ', ');

Upvotes: 1

Related Questions