Iwani Khalid
Iwani Khalid

Reputation: 303

jQuery+Regex: Need help in creating regex

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

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

Upvotes: 2

Views: 36

Answers (2)

anw
anw

Reputation: 160

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

Upvotes: 1

Bryan Elliott
Bryan Elliott

Reputation: 4095

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

Upvotes: 2

Related Questions