Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 242
Rex Pan Avatar asked Feb 17 '23 03:02

Rex Pan


1 Answers

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);
like image 65
Mike Samuel Avatar answered Mar 04 '23 14:03

Mike Samuel