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, '' );
});
4

2 Answers 2

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, '' );
});
Sign up to request clarification or add additional context in comments.

Comments

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, '' );
});

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.