1

I am trying to replace in a formula all floating numbers that miss the preceding zero. Eg:

"4+.5" should become: "4+0.5"

Now I read look behinds are not supported in JavaScript, so how could I achieve that? The following code also replaces, when a digit is preceding:

var regex = /(\.\d*)/,
formula1 = '4+1.5',
formula2 = '4+.5';

console.log(formula1.replace(regex, '0$1')); //4+10.5
console.log(formula2.replace(regex, '0$1')); //4+0.5

1
  • 1
    Try .replace(/\B\.\d/g, '0$&') Commented Dec 15, 2017 at 20:23

2 Answers 2

2

Try this regex (\D)(\.\d*)

var regex = /(\D)(\.\d*)/,
formula1 = '4+1.5',
formula2 = '4+.5';

console.log(formula1.replace(regex, '$10$2'));
console.log(formula2.replace(regex, '$10$2'));

Sign up to request clarification or add additional context in comments.

Comments

1

You may use

s = s.replace(/\B\.\d/g, '0$&')

See the regex demo.

Details

  • \B\. - matches a . that is either at the start of the string or is not preceded with a word char (letter, digit or _)
  • \d - a digit.

The 0$& replacement string is adding a 0 right in front of the whole match ($&).

JS demo:

var s = "4+1.5\n4+.5";
console.log(s.replace(/\B\.\d/g, '0$&'));

Another idea is by using an alternation group that matches either the start of the string or a non-digit char, capturing it and then using a backreference:

var s = ".4+1.5\n4+.5";
console.log(s.replace(/(^|\D)(\.\d)/g, '$10$2'));

The pattern will match

  • (^|\D) - Group 1 (referred to with $1 from the replacement pattern): start of string (^) or any non-digit char
  • (\.\d) - Group 2 (referred to with $2 from the replacement pattern): a . and then a digit

2 Comments

Thanks, the 2nd solution works just fine! Version 1 does not work, since it is possible that the dot is preceeded by letters of functions (eg "ln.05")
@Beppe Glad it worked for you. Note that without ^ alternative, a .5 number at the start of the string would not have been changed to 0.5.

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.