0

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

3 Answers 3

3

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

"put a zero before every number that has exactly one digit"
This doesn't answer the OP's question.
I overlooked that part, its fixed now.
Avinashs answer did it for me but thank you for the explanation why it only matched every second number.
0

use a positive lookahead to see the one digit numbers :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.