Reputation: 135
I have requirement in javascript where the starting and ending of a word is a Character with in between numbers. e.g. S652354536667U
I tried with pattern
(/[A-Z]\d+[A-Z]$/).test(S652354536667U) // returns true ok
(/[A-Z]\d+[A-Z]$/).test(S65235Y4536667U) // returns true needed false
but it is allowing characters in between like S65235Y4536667U is being accepted.
Any help is appreciated.
Thanks
Upvotes: 0
Views: 1355
Reputation: 2834
You need to put ^ at the start and $ at the end in the reg ex. Otherwise if the pattern match anywhere else in the input, it will return true
(/^[A-Z]\d+[A-Z]$/).test(S652354536667U) // returns true
(/^[A-Z]\d+[A-Z]$/).test(S65235Y4536667U) // returns true
Check the below image. It is without specifying the start position. So, from the character 'Y' matching the reg ex
Below is with the starting position
Upvotes: 0
Reputation:
You left caret in the beginning.
["S652354536667U", "S65235Y4536667U"].forEach(item => {
console.log(/^[A-Z]\d+[A-Z]$/.test(item))
})
Upvotes: 2
Reputation: 46
You are missing the ^
. It should be:
^[A-Z]\d*[A-Z]$
You can use this site to quickly test your regex: https://regexr.com/
Upvotes: 1
Reputation: 9073
You need to put a caret at the start of the regex, to indicate the first letter is at the start of the string, i.e.:
^[A-Z]\d+[A-Z]$
Upvotes: 1