8

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?

6
  • 2
    Are you using the regex object for anything else? If not you can obviously just assign the string directly with element.attr("pattern","\\d{5}"). Commented Mar 19, 2013 at 3:05
  • 3
    RegExp instances have a source property which contains their text, so /\d{5}/.source === "\\d{5}". Commented Mar 19, 2013 at 3:31
  • @nnnnnn—there is no need to quote the backslash, \d{5} should do (and does in Firefox). Commented Mar 19, 2013 at 3:43
  • if you are using html5 why not use the data api Commented Mar 19, 2013 at 3:44
  • @RobG - In a string literal (as in my previous comment) you need to escape the backslash, including in FF. In a regex literal you don't escape backslashes. (I know that you know this...) Commented Mar 19, 2013 at 4:09

2 Answers 2

16

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);
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

What's the .data() method? If you're going to assume jQuery you can just save the regex directly as an object...
i dont see anything wrong with this. setting a data attribute is better than setting an element attr
@mkoryak - OP asked about the html5 pattern attribute, which actually has an effect on how the input element behaves. Changing that to a non-attribute data property doesn't help.
Why do you assume jQuery? It isn't a tag, nor in the question or the code.
Didn't know about the "html5 pattern" attribute. Learned something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.