2

I have a website that I'd like to remove some content using jQuery.

I'd like to find anything in my content with this opening symbol [ and closing symbol ] and delete them both including the content in between them.

To be clear, this is actually a Shortcode format from WordPress. And some examples of them include

  • [cudazi_column width='6' class='alpha' ]
  • [cudazi_column_end]
  • [cudazi_column width='6' class='omega' ]
  • [cudazi_slider slide_delay="4000" slide_effect="slide" categories="home" ]

I want to be able to remove these from the content using jQuery

Can anyone point me in the right direction?

I have used this script in the past for another project and was wondering if I could use it again if I managed to get the right regex

$(".content").html(function(i,o){
  return o.replace( /@[0-9:\s]+(am|pm)/ig, '' );
});
Iwani Khalid
  • 303
  • 3
  • 11
  • 1
    [**TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – adeneo Dec 21 '13 at 19:03
  • 1
    That post only applies if you're actually trying to parse complex content in a meaningful way. It does now apply to removing a limited number of syntactically similar tokens such as these. – Jack Dec 21 '13 at 19:04
  • I see. Therefore what I'd like to achieve isn't possible? – Iwani Khalid Dec 21 '13 at 19:06
  • 1
    It is possible but there is a lot of room for error. For example if you include an intentional reference wrapped in those characters such as "The pony he comes [1]", it will also be removed. – Jack Dec 21 '13 at 19:09

2 Answers2

2

The regex to match the string(s) in your description above would be:

/(\[.+\])/

So yes, you could do this:

$(".content").html(function(i,o){
  return o.replace( /(\[.+\])/g, '' );
});
Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22
1

Since [ ] get used to for character ranges in regex (eg: [a-z] for all lower case characters) you need to quote them like:

\[

Both for the opening and closing square brackets:

\[ \]

In between them you want to match everything that is NOT a closing angle bracket:

[^\]]*
  • means one or multiple times. If you would want to keep [] you would use + instead of *

So the later middle part between the start / finish matches you end up with:

\[[^\]]*\]

and of course you'll need / around them:

/\[[^\]]*\]/

and you end up with:

$(".content").html(function(i,o){
  return o.replace(/\[[^\]]*\]//ig, '' );
});
anw
  • 162
  • 2
  • Thank you so much for this and also a step-by-step explanation. I hope I can write simple regex myself in the future so thanks for this really cool explanation! – Iwani Khalid Aug 12 '14 at 18:36