0

I need to use data attribute for regex just as

<div data-regex="REGEX-HERE">

and then get the value by javascript and put in a variable. and then do a test like

var regex = $(this).attr("data-regex");

regex.test(name)

when I tried to use "^[\x20-\x7E]+$" for testing english character is didn't work. Note when I tried this

var regex = /^[\x20-\x7E]+$/;

It worked.

Thanks in advance

7
  • So this ultimately has nothing to do with attributes, but rather creating a regular expression from a string, right? If so, search for that and you'll find lots of answers. Commented Jun 1, 2014 at 18:33
  • 1
    I didn't find. and I think here is simple for beginners (like me) to understand rather than a question with a big piece of code Commented Jun 1, 2014 at 18:38
  • That question is clearly summarized in the title, and the answer shows a single line of code. That link is found as the first google result when searching "javascript create regex from string". Don't know how it can get any easier. It has nothing to do with being a beginner. Being a beginner doesn't excuse you from basic research efforts. Commented Jun 1, 2014 at 18:42
  • Yes sure, my excuse that English isn't my mother tongue and I can't speak / write it probably. I don't know what mean string. I have seen the code in the question you mentioned to, but I didn't understand what is going on. It may be easy for you to understand but for me it is hard. Commented Jun 1, 2014 at 18:49
  • Many people here don't have English as a native language. And even so, the term "string" doesn't help a perfect English speaker either. That is JavaScript language terminology. If you don't know that term, then you've not bothered to learn the basics, which would be another problem. Hard to believe that you know "regex" and "variable" but not "string". Commented Jun 1, 2014 at 18:53

1 Answer 1

2

You can do this:

var regex = new RegExp("^[\x20-\x7E]+$",""); // Modifiers on the tend

So finally:

var regex = new RegExp($(this).data("regex"));

regex.test(name)
Sign up to request clarification or add additional context in comments.

4 Comments

dat w3schools citation tho...
I am aware of the W3 is uncool protocol. But it has an explaination.
new RegExp($(this).data('regex')) is a little nicer
Agree since data attributes are automaticaly tranferred to the data object once called one time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.