How Do I Remove a text Parenthesis Using JQuery?

10,765

You should do the replacing/cleaning with vanilla Javascript. Something like

$('div').text(function(_, text) {
    return text.replace(/\(|\)/g, '');
});

will do it. Notice, this would query for all <div> nodes on the entire side, you want to be more specific on the selector.

demo: http://jsfiddle.net/2gHh2/

If you'd like to remove the parenthesis and everything in between, you'd simply have to change the regular expression to /\(.*?\)/g.

Share:
10,765
user624385
Author by

user624385

Updated on July 23, 2022

Comments

  • user624385
    user624385 almost 2 years

    I have some auto-generated text that includes non-ascii encoded parentheses. For example:

    <div> Some text (these are the non-ascii encoded parenthesis).
    <div>
    

    I want to get rid of the parenthesis. I have the following, which I use elsewhere to clean out some html elements, but I can't get similar to work to remove actual text:

         jQuery(document).ready(function(){jQuery(".block").find("p").remove()});
    

    I've found a few ideas around, but they deal with normal text. Getting rid of a parenthesis is a challenge, as I'm not sure how to code the parenthesis so that jQuery understands it.

    Any ideas?

  • user624385
    user624385 over 12 years
    That works great if the entire div is text, but the div has other elements in it. These are getting obliterated. For example, on your fiddle site, add an <a> element inside the div... it gets ignored, by which I mean it does not get interpreted by the browser and shown as a link.
  • jAndy
    jAndy over 12 years
    @user624385: I've updated the jsfiddle. See jsfiddle.net/2gHh2/2. That should do the job generically for any childnodes within a parentnode too.
  • user624385
    user624385 over 12 years
    Yes! Your answer at jsfiddle.net/2gHh2/2 is perfect! Thank you very much, sir! I've paypal'd you $5 for a coffee. Much obliged.
  • jAndy
    jAndy over 12 years
    @user624385: oh nice, thanks dude. (I'm dreaming of every answer got rewarded by 5 bucks.... hehe)
  • ggomersall
    ggomersall almost 8 years
    the removal of bits between the parenthesis helped a ton as well! thanks jAndy :)