julien c
julien c

Reputation: 57

Checking if JS variable matches a regex pattern

How I can check that my variable match with this pattern A|0, B|0, C| ... Z|0 in jQuery?

The pattern is [one letter]|0

if (myVar.indexOf((/^[A-Z]+$/+'|0') > -1){
  // true;
}

Upvotes: 1

Views: 790

Answers (2)

Hassan Kalhoro
Hassan Kalhoro

Reputation: 190

This following regex can match any integer after |

['A|0', 'A0', 'B|0', '0|C', 'd|0'].forEach(str => {   
   var result =/^[A-Za-z]\|(\d+)$/.test(str);   
   console.log(str, result); 
})

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337691

Given that input your regex should look like this: /^[A-Z]\|0$/. [A-Z] matches the first uppercase character, then the pipe is escaped using \| before looking for the final 0 at the end of the input string. From there you can use test() to check whether the input meets that expression.

['A|0', 'A0', 'B|0', '0|C', 'd|0'].forEach(item => {
  var result = /^[A-Z]\|0$/.test(item);
  console.log(item, result);
})

Upvotes: 1

Related Questions