如何在RegEx模式中使用变量? [英] How to use a variable inside a RegEx pattern?
本文介绍了如何在RegEx模式中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码的用法是仅显示输入的后四位数。
Usage of this code is to show only the last four digits of an input.
这里我要替换此(/。(?=。{4 })/ g,'*')'4',带有变量' 掩码 '。类似的东西。
Here I want to replace this "(/.(?=.{4})/g, '*')" '4' with variable 'mask' . Something like that.
x.value = x.value.replace(/.(?=.{+mask+})/g, '*');
任何建议PLZ
function myFunction(mask) {
var x = document.getElementById("cc");
x.value = x.value.replace(/.(?=.{4})/g, '*');
}
<input type="text" id="cc" onkeyup="myFunction(4)" style="text-align:right">
推荐答案
使用 new RegExp(string)
动态构建正则表达式。文字 /../
表单无法与动态内容一起使用。
Use new RegExp(string)
to build a regular expression dynamically. The literal /../
form cannot be used with dynamic content.
制作确保在构建字符串后有一个有效的模式。
Make sure to have a valid pattern after building the string.
var len = 99;
var re = new RegExp(".(?=.{" + len + "})", "g");
var output = input.replace(re, "*")
另见(和投票支持):
- How do you use a variable in a regular expression?
这篇关于如何在RegEx模式中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文