Justin Carrao
Justin Carrao

Reputation: 45

Javascript regex for string with a number in it

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

Upvotes: 2

Views: 73

Answers (2)

Phil
Phil

Reputation: 164768

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

Upvotes: 2

YLS
YLS

Reputation: 717

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' ]

Upvotes: 1

Related Questions