Search code examples
javascriptregexregexp-replace

Regex Capture Character and Replace with another


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?


Solution

  • 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.