Search code examples
javascriptregex

Add newlines before selected hyphen symbols


I have such a pattern in my text:

PSA-image report on

-15.12.1402 (05.03.2024): 0.15 ng/ml

-19.04.1403 (09.07.2024): 0.36ng/ml.

And I have the above text as a one line string:

let string = `PSA-report on -15.12.1402 (05.03.2024): 0.15 ng/ml -19.04.1403 (09.07.2024): 0.36ng/ml.`

I want to convert the string from the one line format to the format you see in the pattern. I want to insert a newline before every hyphen which has a number directly after it.

I tried this code ...

string = string.replaceAll('-', '\n-');

... but it adds a newline before every hyphen. How do I match just the ones which are directly followed by a number?

let string = `PSA-report on -15.12.1402 (05.03.2024): 0.15 ng/ml -19.04.1403 (09.07.2024): 0.36ng/ml.`
string = string.replaceAll('-', '\n-');
console.log(string);


Solution

  • Use a positive lookahead to detect the presence of a digit following the hyphen.

    let string = `PSA-report on -15.12.1402 (05.03.2024): 0.15 ng/ml -19.04.1403 (09.07.2024): 0.36ng/ml.`
    string = string.replaceAll(/-(?=\d)/g, '\n-');
    console.log(string);

    You can find more information at regex101.