gpt4 book ai didi

javascript - 如何在 JavaScript 中将字符串与括号匹配?

转载 作者:行者123 更新时间:2023-12-03 09:22:03 24 4
gpt4 key购买 nike

这看起来应该是简单直接的,但我一生都无法解决这个问题。

使用 jQuery,我想使用正则表达式将字符串与其括号进行匹配。

这是我要匹配的字符串:(CA)

这是我的正则表达式:(/\(([A-Z]{2})\)/)

我尝试过使用new RegExp("\\(([A-Z]{2})\\)")也是如此。

无论我尝试什么,我总是得到 Unrecognized expression: (CA)我的控制台中出现错误消息。

我做错了什么?任何建议将不胜感激!

谢谢!

编辑 8 月 4 日 @ 9:09 GMT-7

这是我的完整代码:

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

匹配成功后,(CA)将替换为 <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);
});

关于javascript - 如何在 JavaScript 中将字符串与括号匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com