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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With