skip to Main Content

While using a audio plugin for wordpress, the span/class automatically adds parentheses around the text, for example:

`<span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>`

Is there a way to remove the parentheses using JavaScript?

I tried:

$('span.songwriter').text(function(index, text) {
  return text.replace(/(|)/g, '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>

This now works in the snippet and JSFiddle, but parentheses are still present on the page…https://www.cathydvoiceactor.wolfandkey.com/

3

Answers


  1. try this:

    // https://code.jquery.com/jquery-3.7.0.min.js
    
    $('span.songwriter').each(function() {
        $element = $(this);
        $element.html($element.html().replace(/(|)/g, ''));
    });
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>
    
    <br/>
    
    <span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>
    
    <br/>
    
    <span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>
    Login or Signup to reply.
  2. The reason your code doesn’t work is because of a typo, and had you looked at your developer console the error should have been somewhat obvious, see below:

    $('span.songwriter').text(function(text) {
      return text.replace(/(|)/g, '');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>

    The reason that text.replace is not a function is because text isn’t what you think it is; the first argument is the index of the current element in the collection returned by jQuery, and the second is the existing text:

    $('span.songwriter').text(function(index, text) {
      return text.replace(/(|)/g, '');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>

    When jQuery doesn’t work as you expect it’s always worth checking the – excellent, and easily referenced – jQuery documentation to see why.

    References:

    Login or Signup to reply.
  3. If you can’t prevent the html from showing up on the page, you could remove the parentheses using something like this:

    document.querySelectorAll('.songwriter').forEach(
      (span) => span.innerHTML = span.innerHTML.replace(/(|)/g, '')
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search