2

I'm currently working within an AngularJS directive and in the template I'm attempting to check if a an instance variable of the Controller is a certain type of string.

Specifically, this string can be anything at all so long as it has an 8-digit number in it.
Passing Examples: "gdbfgihfb 88827367 dfgfdg", "12345678", ".12345678" The number has to be a solid string of 8 numbers with nothing in between.

I've tried this:

$ctrl.var == /[0-9]{8}/ 

But it doesn't work for some reason. How do I construct a regex in order to do this?

Thanks

4
  • Add "from start to end" /^[0-9]{8}$/. /^\d{8}$/ looks good too. Commented Jun 22, 2016 at 1:43
  • Why it cannot work? Have some logs? Commented Jun 22, 2016 at 1:57
  • Provide more code pls. The regex seems fine. Commented Jun 22, 2016 at 2:00
  • I think you need this: /.*\d{8}.*/ Commented Jun 22, 2016 at 2:01

2 Answers 2

2

Your regex is fine but the comparison is wrong. You want

/\d{8}/.test($ctrl.var)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

let tests = ["gdbfgihfb 88827367 dfgfdg", "12345678", ".12345678", "nope, no numbers here"],
    rx = /\d{8}/;

tests.map(str => document.write(`<pre>"${str}": ${rx.test(str)}</pre>`)) 

Sign up to request clarification or add additional context in comments.

Comments

1

Code:

var first = "gdbfgihfb 88827367 dfgfdg";
var second = "12345678";
var third = ".12345678";

var reg = new RegExp('[0-9]{8}');

console.log(first.match(reg));
console.log(second.match(reg));
console.log(third.match(reg));

Output:

[ '88827367', index: 10, input: 'gdbfgihfb 88827367 dfgfdg' ]
[ '12345678', index: 0, input: '12345678' ]
[ '12345678', index: 1, input: '.12345678' ]

Comments

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.