2

I have an address like this:

117042,ABC DEF,HIJ KLMNOP,9,170

and want to have

117042,ABC DEF,HIJ KLMNOP 9 170

I tried it with this replace Regex

address = address.replace(/,[\d]/g, " ");

but this results in

117042,ABC DEF,HIJ KLMNOP  70

I do not want to replace the digit but still need to check if the digit comes after the comma to not match the other commas.

I am not very good with regex thats why I am asking for help.

1

1 Answer 1

3

You may only replace commas after numbers if they occur at the end of string:

var s = "117042,ABC DEF,HIJ KLMNOP,9,170";
var res = s.replace(/,(\d+)(?=(?:,\d+)*$)/g, " $1");
console.log(res);

The ,(\d+)(?=(?:,\d+)*$) regex matches:

  • , - a comma
  • (\d+) - (Group 1, referred to via $1 from the replacement pattern) one or more digits
  • (?=(?:,\d+)*$) - a positive lookahead that requires 0+ sequences of , + one or more digits at the end of the string.
Sign up to request clarification or add additional context in comments.

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.