4

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?

4

2 に答える 2

9

RegExp instances have a source property which contains their text:

The value of the source property is a String in the form of a Pattern representing the current regular expression.

Therefore

/\d{5}/.source === "\\d{5}"

so your code could be changed to

var regex = /\d{5}/;
element.setAttribute("pattern", regex.source);
于 2013-03-19T03:34:59.717 に答える
-1

If you are using jQuery, use prop instead of attr. Becasue in newer version of jQuery, attr is readonly, prop is read/write.

element.prop('pattern', regex.toString().slice(1,-1));
于 2013-03-19T03:01:17.550 に答える