正则表达式以限制特定字符的出现

时间:2022-08-25 00:29:18

I am looking for aregular expression where I can enter a limit for the number of times a special character appears.

我正在寻找常规表达式,我可以输入特殊字符出现次数的限制。

Example: I have to limit * to a maximum count of 5 in the whole text, so it should be stack***over*f**low.

示例:我必须在整个文本中将*限制为最大计数为5,因此它应该叠加***超过* f **低。

I tried like this in my directive:

我在我的指令中尝试过这样的:

var transformedInput = text.replace(/[^0-9][*]{6}/g, '');

But it's not working. Can someone please help me with this?

但它不起作用。有人可以帮我这个吗?

1 个解决方案

#1


0  

Not sure why you need to replace, perhaps you're trying to prevent anymore asterisks from being entered? In any case, I'd recommend you expand your scope a bit and allow for some more JS to do some of the heavy lifting. If you want to prevent characters from being entered, you can check length of asterisks on every keypress event.

不知道为什么你需要更换,也许你试图阻止进入星号?在任何情况下,我建议你稍微扩大你的范围,并允许更多的JS做一些繁重的工作。如果要阻止输入字符,可以在每个按键事件上检查星号的长度。

var str = 'This* is a ** test string. **';
var count = (str.match(/\*/g) || []).length;
if (count >= 5) {
  alert('doing something...')
}
else {alert(count);}

#1


0  

Not sure why you need to replace, perhaps you're trying to prevent anymore asterisks from being entered? In any case, I'd recommend you expand your scope a bit and allow for some more JS to do some of the heavy lifting. If you want to prevent characters from being entered, you can check length of asterisks on every keypress event.

不知道为什么你需要更换,也许你试图阻止进入星号?在任何情况下,我建议你稍微扩大你的范围,并允许更多的JS做一些繁重的工作。如果要阻止输入字符,可以在每个按键事件上检查星号的长度。

var str = 'This* is a ** test string. **';
var count = (str.match(/\*/g) || []).length;
if (count >= 5) {
  alert('doing something...')
}
else {alert(count);}