1

Trying to replace the special characters preceded by digits with dot.

const time = "17:34:12:p. m.";

const output = time.replace(/\d+(.)/g, '.');
// Expected Output "17.34.12.p. m."
console.log(output);

I had wrote the regex which will capture any character preceded by digit/s. The output is replacing the digit too with the replacement. Can someone please help me to figure out the issue?

user12023283
  • 179
  • 1
  • 1
  • 9

2 Answers2

3

You can use

const time = "17:34:12:p. m.";
const output = time.replace(/(\d)[\W_]/g, '$1.');
console.log(output);

The time.replace(/(\d)[\W_]/g, '$1.') code will match and capture a digit into Group 1 and match any non-word or underscore chars, and the $1. replacement will put the digit back and replace : with ..

If you want to "subtract" whitespace pattern from [\W_], use (?:[^\w\s]|_).

Consider checking more special character patterns in Check for special characters in string.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • :@wiktor - It can be any character besides colon(:). That is the reason I had used `dot`. Initially I used the non word character `\W`, not really sure why is it replacing the digits too. – user12023283 Sep 15 '21 at 12:22
  • @user12023283 `\W` matches a lot of chars, any chars other than ASCII letters, digits or `_`s. You did not capture the digit and it was gone after replacement. You captured the char you replaced, that was your main issue. I see, I replaced your `\W` with `[\W_]` that is used to match any chars other than ASCII alphanumeric chars. If you need to esclude whitespace from it you need `(?:[^\w\s]|_)`. – Wiktor Stribiżew Sep 15 '21 at 12:23
  • 1
    Ohh Okay. Got it. Thank you so much for clarification :) – user12023283 Sep 15 '21 at 12:25
1

You should look for non word(\w) and non spaces (\s) characters and replace them with dot.

You should use some live simulator for regular expressions. For example regex101: https://regex101.com/r/xIStHH/1

const time = "17:34:12:p. m.";

const output = time.replace(/[^\w\s]/g, '.');
// Expected Output "17.34.12.p. m."
console.log(output);
Daniel Hornik
  • 1,957
  • 1
  • 14
  • 33
  • 1
    I want to add that `[^\w\s]` does not match an underscore, that is a specific char since it belongs to both special (it is matched with `\p{P}`, `/\p{P}/u.test('_')`) and word characters (check `/\w/.test('_')`). Hence, when OP says "special chars" and you suggest `[^\w\s]`, I think it would be valuable to always mention that `_` can be added to the pattern if need be via `[^\w\s]|_`. Or, `(?:(?!\s)[\W_])`. – Wiktor Stribiżew Sep 16 '21 at 08:48