英文:
jQuery replace span contains comma with single comma
问题
我想要将<span class="test">,</span>替换为,,我已经尝试了以下代码:
if($('.elq-form').hasClass('elq-form')) {
   $(".elq-form").html( $(".elq-form").html().replace(/<span class="test">,</span>/g,",") ); }
} 
我收到了如下错误:
> Uncaught SyntaxError: Invalid regular expression flags
如何用逗号,替换span标签?
英文:
I want to replace <span class="test">,</span>  to , I have tried as
if($('.elq-form').hasClass('elq-form')) {
   $(".elq-form").html( $(".elq-form").html().replace(/<span class="test">,</span>/g,",") ); }
} 
I'm getting
> Uncaught SyntaxError: Invalid regular expression flags
how to replace the span tag with comma(,) ?
答案1
得分: 5
只需使用 unwrap。
$(".elq-form").find('span.test').contents().unwrap();
.test {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elq-form">
  <span class="test">,</span>
  <a>Blah Blah</a>
  <span class="test">,</span>
  <p>Blah Blah</p>
</div>
英文:
Simply use unwrap
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$(".elq-form").find('span.test').contents().unwrap();
<!-- language: lang-css -->
.test {
  color: red;
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elq-form">
  <span class="test">,</span>
  <a>Blah Blah</a>
  <span class="test">,</span>
  <p>Blah Blah</p>
</div>
<!-- end snippet -->
答案2
得分: 1
/在正则表达式中具有特殊含义,您必须转义(\/)它:
$(".elq-form").html( $(".elq-form").html().replace(/<span class="test">,<\/span>/g,",") );
英文:
/ has special meaning in RegEx, you have to escape (\/) that:
$(".elq-form").html( $(".elq-form").html().replace(/<span class="test">,<\/span>/g,",") );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论