简体   繁体   中英

How can I match a string with parenthesis in JavaScript?

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: (/\\(([AZ]{2})\\)/)

I've tried using new RegExp("\\\\(([AZ]{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"/>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM