使用jQuery替换包含逗号的标签内的逗号为单个逗号。

huangapple go评论66阅读模式
英文:

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

$(&quot;.elq-form&quot;).find(&#39;span.test&#39;).contents().unwrap();

<!-- language: lang-css -->

.test {
  color: red;
}

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;div class=&quot;elq-form&quot;&gt;
  &lt;span class=&quot;test&quot;&gt;,&lt;/span&gt;
  &lt;a&gt;Blah Blah&lt;/a&gt;
  &lt;span class=&quot;test&quot;&gt;,&lt;/span&gt;
  &lt;p&gt;Blah Blah&lt;/p&gt;
&lt;/div&gt;

<!-- end snippet -->

答案2

得分: 1

/在正则表达式中具有特殊含义,您必须转义(\/)它:

$(&quot;.elq-form&quot;).html( $(&quot;.elq-form&quot;).html().replace(/&lt;span class=&quot;test&quot;&gt;,&lt;\/span&gt;/g,&quot;,&quot;) );
英文:

/ has special meaning in RegEx, you have to escape (\/) that:

$(&quot;.elq-form&quot;).html( $(&quot;.elq-form&quot;).html().replace(/&lt;span class=&quot;test&quot;&gt;,&lt;\/span&gt;/g,&quot;,&quot;) );

huangapple
  • 本文由 发表于 2020年1月6日 21:06:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定