如何用逗号替换空格,然后在jquery中替换空格?

时间:2019-09-11 23:56:09

标签: javascript jquery

我正在将一些html复制到textarea中,并尝试通过将div分为h3和h3以及<ul> and <li>标签来格式化当前textarea。

// 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>

我的代码:

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



    }); 

我正试图让它阅读

output: comment1, comment2

我已经尝试过了,但是没有用。

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

错误未捕获的错误:语法错误,无法识别的表达式:,

谢谢大家

3 个答案:

答案 0 :(得分:3)

如果在第二个表达式之前不包含let,则它应保持原样。您不能使用let(或var)声明两次变量。

答案 1 :(得分:1)

尝试:

printf

答案 2 :(得分:0)

我测试了此代码,它看起来运行得很好!

var string = "blah blah blah";
var formattedString = string.replace(/ /g, ', ');
相关问题