Reputation: 429
I select all classes by class that begins with photo-
. Replace part of class name by pattern. I need to replace photo-gallery-RID459852
with photo-gallery
. Note: the part -RID[0-9]
is replaced by ""
$("#Master [class*='photo-']").replace(function(index, css) {
return (css.match(/(^|\s)-RID\S+/g) || []).join(' ');
}, "");
<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>
My jsFiddle: https://jsfiddle.net/ngqku78p/
Upvotes: 1
Views: 471
Reputation: 177851
Perhaps you meant this?
You could loop over the classList but this works for your examples too
$("#Master [class*='photo-']").each(function() {
console.log("Before", this.className)
this.className = this.className.replace(/photo-gallery-RID.*? /g, "photo-gallery ");
console.log("After ", this.className)
});
.photo-gallery {
font-weight: bold;
}
.other {
font-style: italic;
}
<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">RID987410</div>
<div>
<div>
<div class="photo-gallery-369841 other any some">369841</div>
</div>
</div>
<article>
<div class="photo-gallery-RID36541 here now other any some">RID36541</div>
</article>
</main>
Upvotes: 2
Reputation: 337560
Your current code doesn't work as jQuery objects do not have a replace()
method.
To achieve the output you require you could loop over every class on the element and remove the RIDXXX
from it's name. To do that you can use the classList
collection along with the replace()
method, like this:
$("#Master [class*='photo-']").each(function(i, el) {
el.classList.forEach(function(className) {
el.classList.replace(className, className.replace(/\-RID\d+/g, ''));
});
});
.photo-gallery {
color: #C00;
}
<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">Lorem</div>
<div>
<div>
<div class="photo-gallery-369841 other any some">ipsum</div>
</div>
</div>
<article>
<div class="photo-gallery-RID36541 here now other any some">dolor</div>
</article>
</main>
Upvotes: 3