Rex Pan
Rex Pan

Reputation: 2420

Assign Regex object to html input pattern

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?

Upvotes: 8

Views: 4112

Answers (2)

Mike Samuel
Mike Samuel

Reputation: 120506

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);

Upvotes: 16

deerchao
deerchao

Reputation: 10544

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));

Upvotes: -1

Related Questions