javascript 查找并替换字符串中的动态模式
我有一个动态模式,我一直在使用下面的代码来发现
var matcher = new RegExp("%" + dynamicnumber + ":", "g");
var found = matcher.test(textinput);
我需要该模式来满足新的要求,即包含 y 或 n 的附加尾随 5 个字符。然后删除它或用“”(什么都没有)替换它。
我尝试了该模式的语法,但显然它不起作用。
var matcher = new RegExp("%" + dynamicnumber + ":" + /([yn]{5})/, "g");
如有任何提示,TIA 表示赞赏
。
I have a dynamic pattern that I have been using the code below to find
var matcher = new RegExp("%" + dynamicnumber + ":", "g");
var found = matcher.test(textinput);
I need the pattern to have a new requirement, which is to include an additional trailing 5 characters of either y or n. And then delete it or replace it with a '' (nothing).
I tried this syntax for the pattern, but obviously it does not work.
var matcher = new RegExp("%" + dynamicnumber + ":" + /([yn]{5})/, "g");
Any tip is appreciated
TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该只将正则表达式字符串传递到 RegExp c'tor 中:
You should only pass the regex string into the RegExp c'tor :
然后将其替换为第一个捕获组的内容。
Then replace it with the contents of the first capture group.
使用引号而不是斜杠:
此外,请确保
dynamicnumber
或number
是有效正则表达式。特殊字符必须以双斜杠作为前缀,\\
,文字双斜杠必须写为四个斜杠:\\\\
。Use quotes instead of slashes:
Also, make sure that
dynamicnumber
ornumber
are valid RegExps. special characters have to be prefixed by a double slash,\\
, a literal double slash has to be written as four slashes:\\\\
.