Praind
Praind

Reputation: 1571

Replace function does only replace every second regex match

I would like to use regex in javascript to put a zero before every number that has exactly one digit.

When i debug the code in the chrome debugger it gives me a strange result where only every second match the zero is put.

My regex

"3-3-7-3-9-8-10-5".replace(/(\-|^)(\d)(\-|$)/g, "$10$2$3");

And the result i get from this

"03-3-07-3-09-8-10-05"

Thanks for the help

Upvotes: 0

Views: 161

Answers (3)

aelor
aelor

Reputation: 11116

use a positive lookahead to see the one digit numbers :

"3-3-7-3-9-8-10-5".replace(/(?=\b\d\b)/g, "0");

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Use word boundaries,

(\b\d\b)

Replacement string:

0$1

DEMO

> "3-3-7-3-9-8-10-5".replace(/(\b\d\b)/g, "0$1")
'03-03-07-03-09-08-10-05'

Explanation:

  • ( starting point of first Capturing group.
  • \b Matches between a word character and a non word character.
  • \d Matches a single digit.
  • \b Matches between a word character and a non word character.
  • ) End of first Capturing group.

Upvotes: 3

anubhava
anubhava

Reputation: 784958

You can use this better lookahead based regex to prefix 0 before every single digit number:

"3-3-7-3-9-8-10-5".replace(/\b(\d)\b(?=-|$)/g, "0$1");
//=> "03-03-07-03-09-08-10-05"

Reason why you're getting alternate prefixes in your regex:

"3-3-7-3-9-8-10-5".replace(/(\-|^)(\d)(\-|$)/g, "$10$2$3");

is that rather than looking ahead you're actually matching hyphen after the digit. Once a hyphen has been matched it is not matched again since internal regex pointer has already moved ahead.

Upvotes: 0

Related Questions