skip to Main Content

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 hyphen before every newline. 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);

2

Answers


  1. You could try

    string.replace(/(?=-d)/g, 'n')
    
    let string = `PSA-report on -15.12.1402 (05.03.2024): 0.15 ng/ml -19.04.1403 (09.07.2024): 0.36ng/ml.`
    
    const formatted = string.replace(/(?=-d)/g, 'n');
    
    console.log(formatted);
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search