Sing2
Sing2

Reputation: 97

Weird return javascript regex without flag 'g'

code = DAK~ 800 SUB~10/21/2015 CAK~10/21/2015

i just want to get 800

wheh i use this regex:

code_fix = match(/([0-9]){3}/g) It returns = [ '800', '201', '201' ]

but when i try use the regex without flag g why is what my result looks like:

[ '800',
  '0',
  index: 21,
  input: 'DAK~ 800 SUB~10/21/2015 CAK~10/21/2015' ]

Upvotes: 1

Views: 60

Answers (2)

Kerwin
Kerwin

Reputation: 1212

If use ([0-9]){3}, it also two matched,800 is all match, and 0 is group match by ([0-9]), it match the last 0 in 800

Upvotes: 0

leeor
leeor

Reputation: 17801

You need a word-boundary. Try this:

/\b([0-9]){3}\b/g

See this reference for more on word boundaries.

Upvotes: 1

Related Questions