0

This seems like it should be easy and straight-forward but I can't solve this for the life of me.

Using jQuery, I want to match a string with its parentheses using Regex.

This is the string I'm trying to match: (CA)

This is my Regex: (/\(([A-Z]{2})\)/)

I've tried using new RegExp("\\(([A-Z]{2})\\)") as well.

No matter what I try I always end up with the Unrecognized expression: (CA) error message in my console.

What am I doing wrong? Any advice would be much appreciated!

Thanks!

EDIT Aug. 4 @ 9:09 GMT-7

Here is my full code:

<div class="athlete-name">Random Joe</div> <div class="high-school">Jonah Lomu Senior (CA)</div>

Upon successful match, the (CA) will be replaced with <img src="/img/flag/ca.svg"/>

4
  • 1
    Can you provide a full example of your code. Also, Are you trying to match including or excluding the brackets? Commented Aug 4, 2015 at 15:02
  • This has nothing to do with jQuery. Commented Aug 4, 2015 at 15:08
  • Why do you use double parens in Regex (before and after escaped one)? Commented Aug 4, 2015 at 15:09
  • @hindmost Because with jQuery, if you're going to use the meta characters as a literal part of the code, they have to be escaped with \\ preceding them. See here: api.jquery.com/category/selectors Commented Aug 4, 2015 at 15:15

1 Answer 1

1

This is the regex that you want to match the string.

(\([A-Z]{2}\))

Here's how it would work.

var s = "(CA)";
var r = /(\([A-Z]{2}\))/;

if(r.test(s)){
    alert('Matched!');
}

Give your edit, here's how it might be used.

$('div').each(function() {
    var s = $(this).html();
    var r = s.replace(/(\([A-Z]{2}\))/, '<img src="/img/flag/ca.svg"/>');  
    $(this).html(r);
});
Sign up to request clarification or add additional context in comments.

4 Comments

It gives me this in the console: Uncaught TypeError: Cannot read property 'ownerDocument' of undefined
I deleted my answer and upvoted yours as this really isn't a regex question and you seem to have a handle on this.
Any idea how to get around the Uncaught Error: Syntax error, unrecognized expression: (CA) error message? That's currently what's holding me up.
@DaveyJake You need to post your javascript code as well, and possibly the line number that you're getting the error on.

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.