将Regex对象分配给html输入模式 [英] Assign Regex object to html input pattern
本文介绍了将Regex对象分配给html输入模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要以编程方式将一个正则表达式对象分配给输入元素模式属性。
以下是我当前的实现:
I need to assign a regex object to an input element pattern attribute programmatically. Below is my current implementation:
var regex = /\d{5}/;
element.attr("pattern", regex.toString().slice(1,-1);
在没有字符串操作的情况下有更好的方法吗?
Is there a better way to do this without string manipulation?
推荐答案
RegExp
实例有 来源
属性,其中包含其文本:
RegExp
instances have a source
property which contains their text:
源属性的值是一个String的形式,表示模式当前正则表达式。
The value of the source property is a String in the form of a Pattern representing the current regular expression.
因此
/\d{5}/.source === "\\d{5}"
所以您的代码可以更改为
so your code could be changed to
var regex = /\d{5}/;
element.setAttribute("pattern", regex.source);
这篇关于将Regex对象分配给html输入模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文