Remove / Replace dashes in classes

Let’s say I have .contents() of HTML. How can I remove all dashes (secondary method is I need a .replace()) only within class=“” (e.g. class=“asdf-asdf” would turn out to class=“asdfasdf”).

I did search but I’m having trouble finding the correct search terms. There are examples of removing dashes via .replace() but I don’t know how to combine that to look only within the class attribute?

1 Like

You’ll need a regex that matches the class="..." pattern and do a global replace.
This replaces all dashes in class names with underscores.

var html = `
<div class="a-b-c">
  <p class="asdf asdf-asdf">Hello</p>
</div>
`;
var regex = /class="(.*?)"/g;
var newHtml = html.replace(regex, function(className) {
  return className.replace(/-/g, '_');
})

console.log(newHtml)

Hmm, thanks for that. I really appreciate it. It’s erroring out for me though

var twt =  $(obj).find('iframe[id*="twitter-widget"]').contents();
      
      var tweets = twt.find('.timeline-TweetList-tweet');
      var regex = /class="(.*?)"/g;
      var newtweets=tweets.replace(regex, function(className) {
        return className.replace(/-/g, '_');
      })

http://cod ere po.d em o.fin alsi te.com/bp t/mas hup2

This doesn’t change with it being in an iframe, does it?

Hmmm, the error message isn’t helping me at all

TypeError: n.replace is not a function
renderTweets/t<()

I’m trying to wait until after I append…thinking maybe modifying content in the iframe is an issue. But…this doesn’t work either

tweets.each(function(i){
        if(i<show+1){
          $(".tweets").append('<li></li>');
          $(this).children().appendTo($(obj).find('.tweets > li:last-child'));

          var lastChild = $(obj).find(".tweets > li:last-child");
          var regex = /class="(.*?)"/g;
          lastChild=lastChild.replace(regex, function(className) {
            return className.replace(/-/g, '_');
          });
          console.log(lastChild);
        }
      });

Replace is a function on strings not a DOM selection.

You probably want to do twt.find('.timeline-TweetList-tweet').html()

Thanks! Now it’s not erroring out, and appears to be console logging the right stuff, but it’s not actually replacing.

var lastChild = $(obj).find(".tweets > li:last-child").html();
          var regex = /class="(.*?)"/g;
          lastChild=lastChild.replace(regex, function(className) {
            console.log(className.replace(/-/g, '_'));
            return className.replace(/-/g, '_');
          });

I know .replace() doesn’t actually replace unless you overwrite the variable (a.k.a. why I did lastChild=lastChild) but it doesn’t seem to have overridden?

I was wondering if “n” was "n"odelist.

Maybe you can avoid the regex?


<div>
<p class="foo-bar">First Foo Bar paragraph</p>
<p class="foo-baz">First Foo Baz paragraph</p>
<p class="foo-quux">First Foo Quux paragraph</p>
<p class="foo-norf">First Foo Norf paragraph</p>
<p class="foo-bar">Second Foo Bar paragraph</p>
<p class="bar-baz">Bar Baz paragraph</p>
<p class="baz-quux">Baz Quux paragraph</p>
<p class="quux-norf">Quux Norf paragraph</p>
<p class="bar-foo">Bar Foo paragraph</p>
<p class="foo-baz">Second Foo Baz paragraph</p>
<p class="foo-quux">Second Foo Quux paragraph</p>
<p class="foo-norf">Second Foo Norf paragraph</p>
</div>
<script>
// script that needs the DOM to be loaded here
var targ_elems = document.querySelectorAll("p[class|=foo]");
for (var i = 0; i < targ_elems.length; i++) {
  targ_elems[i].setAttribute('class', "replaced");
}
</script>

I don’t think that will work Mitt; I just want the dashes removed, not to have a universal class for all the elements inside :confused: .Thanks though.

You might have to insert new classes and remove old ones as two separate steps.

Yes, you’re only updating the html in the lastChild variable, not applying it back to the DOM.

var $el = $(obj).find(".tweets > li:last-child")
var html = $el.html();
var regex = /class="(.*?)"/g;
html = html.replace(regex, function(className) {
  return className.replace(/-/g, '');
});
$el.html(html);

Your initial question led me down the string replacement path but jQuery has a way simpler way to achieve this. This version will only update the className’s that need updating, the previous will replace the whole elements innerHTML.

$('[class*="-"]').each(function(el) {
  el.className = el.className.replace(/-/g, '');
})
1 Like

Thank you!!

You won’t believe this, but I changed that to replace the dash with a dash, and now I have styling working in Safari. I KNEW those dashes were corrupt…thank you thank you!

1 Like

Sounds like an encoding problem to me, to confirm you can try logging the charCode of the two dash characters, I suspect they’ll give you two different numbers.

"-".charCodeAt(0)

Yes, and I suspect Word is involved eg.

&#8209; is not &#45;

‑ is not -

1 Like

Sorry, how do I use that snippet mark? Or rather, how do I grab a dash from the twitter and use that?

Just that snippet alone are returning “45”. But I suspect to get good results, I’ll need a dash from the twitter page.

I tried this, but no go (I also tried yours exactly as you had it).

console.log($this).indexOf("-").charCodeAt(0));

Copy and paste?

I’m assuming the character you’re replacing is inside the regex /-/

I did copy/paste, but it returned “45” for all browsers.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.