使用jQuery正则替换以photo-开头的类名指定部分
解决类名中移除
-RID加数字后缀的问题 我来帮你搞定这个类名替换的需求——你需要选中所有包含以photo-开头类的元素,把类名里-RID后面跟一串数字的部分删掉,比如photo-gallery-RID459852要变成photo-gallery对吧?
首先得说下你原来的代码存在的问题:jQuery并没有直接的.replace()方法能这么调用,而且你用的正则/-RID\S+/g会匹配所有-RID后面的非空白字符,可能会误删掉后面的其他类名,逻辑上不太对。
修正后的方案
我们可以通过遍历目标元素,直接操作元素的className属性,用精准的正则来替换目标内容:
基础版(移除所有类名中的-RID+数字)
这个方案会把元素所有类名里符合-RID加数字的部分都删掉,适合确定只有photo-开头的类会有这种后缀的场景:
$(function() { // 选中#Master下所有类名包含photo-的元素 $("#Master [class*='photo-']").each(function() { // 替换所有-RID后跟数字的部分为空 this.className = this.className.replace(/-RID\d+/g, ''); }); });
精准版(只修改photo-开头类的后缀)
如果担心其他类名里也有-RID+数字的结构不想被修改,可以用更精准的正则,只匹配photo-开头的类后面的-RID+数字:
$(function() { $("#Master [class*='photo-']").each(function() { // 只保留photo-开头类的核心部分,去掉-RID+数字后缀 this.className = this.className.replace(/(photo-\w+)-RID\d+/g, '$1'); }); });
完整示例代码
把代码放到你的HTML里,就能正常工作了:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <main id="Master"> <div class="photo-gallery-RID459852 other any some"> Algo </div> <div class="photo-gallery-RID987410 other any some2 other2"></div> <div> <div> <div class="photo-gallery-369841 other any some"></div> </div> </div> <article> <div class="photo-gallery-RID36541 here now other any some"></div> </article> </main> <script> $(function() { $("#Master [class*='photo-']").each(function() { this.className = this.className.replace(/(photo-\w+)-RID\d+/g, '$1'); }); }); </script>
效果说明
运行后各个元素的类名会变成:
photo-gallery other any somephoto-gallery other any some2 other2photo-gallery-369841 other any some(这个因为没有-RID前缀的数字后缀,所以保留原样,符合需求)photo-gallery here now other any some
内容的提问来源于stack exchange,提问作者Renato Ramos
相关产品推荐
相关产品推荐

